[英]C Get size of Array of array of chars
我想獲取 Text 數組中的元素數,答案應該是 2
char Text[5][10] = {
"Big12345",
"Big54321",
};
我想要一個代碼來計算字符數組中的元素數
你誤會了。 數組中的元素數量為 5。兩個元素具有非空字符串,三個元素具有空字符串。 但實際上空字符串可以放在數組的任何位置。 例如
char Text[5][10] =
{
"Big12345",
"",
"Big54321",
};
這個聲明等價於
char Text[5][10] =
{
"Big12345",
"",
"Big54321",
"",
""
};
您可以編寫一個 function 來確定有多少元素包含非空字符串。 例如
#include <stdio.h>
size_t count_non_empty( size_t m, size_t n, char s[][n] )
{
size_t count = 0;
for ( size_t i = 0; i < m; i++ )
{
count += s[i][0] != '\0';
}
return count;
}
int main(void)
{
char Text[5][10] =
{
"Big12345",
"",
"Big54321",
};
printf( "There are %zu non-empty elements\n", count_non_empty( 5, 10, Text ) );
return 0;
}
程序 output 是
There are 2 non-empty elements
在這種特殊情況下,初始化器之后的任何內容都將為0
,因此:
size_t counter = 0;
while ( Text[counter][0] != 0 )
counter++;
但是,一般來說,C 並沒有為您提供這樣做的好方法。 您要么必須跟蹤單獨使用的元素數量,要么必須在數組中使用哨兵值。
使用以下命令查找數組中分配有字符串的元素數:
#include <stdio.h>
#include <string.h>
int main()
{
char Text[5][10] = {"Big12345",
"Big54321",};
int i, n;
for(i = 0, n = 0 ; i < 5 ; i++)
if(strlen(Text[i]) > 0)
n += 1;
printf("%d elements have a length > 0\n", n);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.