我知道字符串文字存储在只读内存中,因此您无法更新它们。但是 strlen() 函数有什么问题。如果我在程序中初始化 char *s,它就会起作用。即
char *s="hey";
length=strlen(s);
printf("%d\n",length);// this works
从用户处获取字符串时不会
char *s;
int length;
scanf("%s",s);
length=strlen(s);
printf("%d\n",length); //this doesn't. gives segmentation fault
最佳答案
您必须在要读取字符串的位置分配内存。例如
char s[20] = { '\0' };
int length;
scanf("%19s",s);
length=strlen(s);
printf("%d\n",length);
如果你这样声明 s
char *s;
则指针未初始化。
如果你这样声明 s
char *s="hey";
然后 scanf 将尝试更改导致程序未定义行为的字符串文字。
关于c - 从用户获取字符串并使用 strlen() 查找其长度时出现段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32036209/