簡體   English   中英

如何獲取char數組中的元素個數?

[英]how to get number of elements in char array?

我有這些 2 arrays:

     char *names[] = {"Marie","Pascale","Valarie","Juanita"};
     int ages[] = {35, 38, 42, 48};

     // this returns the number of elements in the int array
     int compte = sizeof(ages)/sizeof(int);

如何獲取 char 數組中的元素數?

只是間接地,因為您有一個終止的 null 字節,而不是保存的大小或實際數組。

#include <string.h>
/*...*/
int c_names  = sizeof names / sizeof*names;
for (int i = 0; i < c_names; i++)
    printf("%zu %s %p\n", strlen(names[i]), names[i], names[i]);

這給出了names中字符指針的內容長度、內容和地址(參考內容):

5 Marie 0x555c45587004
7 Pascale 0x555c4558700a
7 Valarie 0x555c45587012
7 Juanita 0x555c4558701a

無需對 arrays 和指針過於哲學化:這是一個很好的說明。 如果“Marie”可以有任何長度,則不可能知道“Pascale”從哪里開始。 “瑪麗”節省空間,但對 alignment 不利。


如何獲取 char 數組中的元素數?

通過循環直到找到 null 字節又名strlen() 您並沒有真正分配任何 char 數組或終止它,編譯器確實如此,但您可以安全地讀取字符直到\0

出於同樣的原因(所謂的字符串文字)名稱可能是const

 printf("%c\n", names[2][0]); // OK prints 'V'
 names[2][0] = 'F';           // Segm. Fault 

因此,“char 數組”在這種情況下具有誤導性。 Arrays 分配給時不會出現段錯誤。

由於names是一個指針數組,因此可以用與年齡相同的方式計算它:

int num_names = sizeof(names) / sizeof(char *);

此外,您可以這樣做:

int num_names = sizeof(names) / sizeof(*names);

ages也一樣:

int compte = sizeof(ages) / sizeof(*ages);

如果您的意思是由names的每個元素指向的數組,您只能間接地這樣做,就像@chezfilou 提到的那樣,使用strlen

現在,如果你想讓它更容易處理,你可以使用一個結構,如下所示:

struct person {
    const char *name;
    unsigned age;
} persons[] = {
    {.name = "Marie",   .age = 35,},
    {.name = "Pascale", .age = 38,},
    {.name = "Valarie", .age = 42,},
    {.name = "Juanita", .age = 48,},
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM