c - C中数组内的元素数

标签 c arrays

我有一个数组,想找出其中元素的数量。 我想要的是:

char array[100];

array[0] = 'a';
array[1] = 'b';
array[2] = 'c';

本例中的元素个数为 3。 这就是我想要的。

我怎样才能找到那个值?

最佳答案

如果你这样做

char array[100];
printf("%s", array); 

你会得到 abc。要查找 char 数组的元素,您可以使用 strlen() 函数。

printf("%zu", strlen(array)); //would give you 3

strlen() 在遇到 \0 空元素之前返回内部有值且不是垃圾内存的元素数。

关于strlen()函数,因为评论员问我为什么

http://www.cplusplus.com/reference/cstring/strlen/ 拍摄

获取字符串长度

The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself). This should not be confused with the size of the array that holds the string. For example:

char mystr[100]="test string"; 

defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.

由于人们对空终止符有顾虑..

您可以使用memset() 函数将所有元素设置为空。

char array[100];
memset(&array, '\0', 100);

当您声明元素时,您可以将最后一个元素设置为空终止符。

char array[100];

int elemenNum = 0;

array[elemenNum] = 'a';
elemenNum++;
array[elemenNum] = 'b';
elemenNum++;
array[elemenNum] = 'c';
elemenNum++;
array[elemenNum] = '\0'; //Null terminator
elemenNum++;

或者您可以手动设置数字。随心所欲。

最后,正如 Lee 在评论中提到的,

And of course all of this only works if you set values in order, 0, 1, 2, 3... If you set #1, then #2, then #5, then #9, strlen() will not work.

关于c - C中数组内的元素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46778918/

相关文章:

c - 汇编语言是如何工作的?

javascript - 为什么 console.log() 创建/**id :4**/and/**ref:4**/values?

javascript - 将某些数组元素移到数组前面

java - Java 的 Arrays.asList() 是否违反了 OOP?

c# - 2维结构表

c - 链表问题

c - 如何快速捕获无效的枚举

c - 无论输入什么数值,输出均为 0.00 浮点值

c++求和使用for循环和二维数组

php - 动态访问 PHP 数组