该功能getStringEnd()无法正常工作,但我不知道为什么.该函数不返回字符串结尾的正确值.我已经发现变量max计算不正确.
但
int max = sizeof str / sizeof (char);
应该工作,不应该吗?
你有什么想法?
#include <stdio.h>
#define MAX_FIGURES 30
int getStringEnd(const char * str);
int getStringEnd(const char * str)
{
int max = sizeof str / sizeof (char);
int counter = 0;
while (counter <= max -1)
{
if ((str[counter] == '\0') || (str[counter] == '\n')) return counter;
counter += 1;
}
return 0;
}
int main(void)
{
char figures[MAX_FIGURES];
for (int i = 0; i <= MAX_FIGURES - 1; i++) figures[i] = '\0';
fgets(figures, MAX_FIGURES, stdin);
int stringEnd = getStringEnd(&figures);
}
Run Code Online (Sandbox Code Playgroud)
在getStringEnd()功能上,str是一个const char *,没有别的.sizeofoperator返回数据类型的大小,而不是变量指向的内存量.
您需要使用strlen()来获取字符串的长度.你需要写一些类似的东西
int max = strlen(str); // sizeof(char) == 1, fixed, can be ommitted
Run Code Online (Sandbox Code Playgroud)
注意:FWIW,请记住,strlen()没有考虑终止空值.