#include <stdio.h>
#include <stdlib.h>
int countArrayChars(char *strArray[]){
int i=0;
while (strArray[i] != '\0'){
i++;
}
printf("%d\n", i);
return i;
}
int main(int argc, const char * argv[]) {
char *dog[] = {"dog"};
countArrayChars(dog);
出于某种原因,它打印“5”。
它不应该打印 3 吗? 我什至尝试将\0 放在“g”之后。
最佳答案
您声明字符串数组并使用dog
对其进行初始化。
char *dog[] = {"dog"};
实际上它表示为
dog[0] = "Dog"; //In your case only element index with 0.
...............
...............
dog[n] = "tiger"; //If there Have n+1 element
因此您的数组大小为 1。其中包含常量字符串 dog
。要访问它,您应该使用 dog[0]
。
因此,无需进行较少的修改,您就可以将代码用作:
int countArrayChars(char *strArray[])
{
int i=0;
while (strArray[0][i] != '\0')
{
i++;
}
printf("%d\n", i);
return i;
}
int main(int argc, const char * argv[])
{
char *dog[] = {"dog"};
countArrayChars(dog);
}
或者如果你想声明一个字符串使用
char *dog = "dog";
或
char dog[] = "dog";
关于c - 在 c 中计算数组时得到错误的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33114908/