![](/img/trans.png)
[英]How to get an array size in a function without counting or passing the length as a parameter?
[英]Counting the length of an array with a function C
我的代码有错误,我正在尝试编写一个 function 来计算字符串的字符长度。 我正在尝试将字符串放入数组中,以便可以使用 function 来返回字符串的长度。 如果用户输入dad
程序打印len of string value: 3
等等。 错误error: subscripted value is neither array nor pointer nor vector
。
Function 为字符串的长度:
int stringcounter(a){
int count;
while (true){
if (a[count] != NULL){
++count;
}
else{break;}
}
return count;
}
主function
int main(void) {
char text[100]; //string
char str[100]={0}; // storing the text string
printf("Enter an interesting string of less than %d characters:\n", 100);
scanf("%s",text);
str[1] = text;
stringcounter(str);
printf("len of string value: %d", count);
return 0;
}
有很多错误。 首先将 function 中的计数初始化为 0: int count = 0;
因为如果你不初始化它,它会被设置为任何值。 其次,字符串计数器 function 中的计数变量仅在字符串计数器 function 的 scope 中,您不能在 main 中访问它,因为在查找全局变量时应谨慎使用。
您没有将 function 的返回值存储在任何地方,因此将其存储在某个变量中。 尽量避免使用 while(true),因为你可以在无限循环中结束。 你的条件可以是你的 if,所以虽然 char 不是 NULL。
同样使用 str[1] 您正在访问一个字符,您需要指针数组才能使其成为字符串数组。 我猜你才刚刚开始,所以它太高级了,你不需要str[1] = text;
一点也不。 例如,您可以像处理文本一样初始化字符串,在其中输入输入,然后将其发送到函数中,计算长度并将其返回到某个变量中。 不需要第二个字符串变量。 是的,您需要声明参数类型。 您可以使用int stringcoutner(char *a)
或int stringcounter(char a[])
。
我不想给你写解决方案,但我希望它会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.