[英]C - Program segfaulting when scanf() is called
我现在正在学习C,我直接从正在使用的书中复制了这个小片段。 当我运行它时它会出现段错误,我不知道为什么,我在gdb中运行它,并在第9行scanf(“%s”,aName)处停止;但是打印变量的值不会带来任何可疑的外观。 这东西怎么了
#include <stdio.h>
int nameLength(char[]);
main () {
char aName[20] = {'\0'};
printf("\nEnter your first name: ");
scanf('%s', aName);
printf("\nYour first name contains %d letters.", nameLength(aName));
}
int nameLength(char name[]) {
int result = 0;
while (name[result] != '\0') {
result++;
}
return result;
}
编辑:我忘了提,它甚至没有显示提示或让我输入名称。 执行后立即崩溃。
在清单中,您使用'%s'
而不是"%s"
-注意单引号和双引号之间的区别。 单引号分隔字符,双引号分隔字符串。 scanf()
采用字符串首个参数,因此需要双引号。
scanf('%s', aName);
使用双引号:
scanf("%s", aName);
或确定:
scanf("%19s", aName);
将字符串限制为19个字符
尝试用以下方法替换scanf行:
scanf ("%s", aName);
请注意双引号。
...里奇
在scanf中使用双引号
如果这是计算字母数的练习,则可以执行以下操作,但要使用指针。
int nameLength(char *name)
{
int i = 0;
while(*name++) {
i++;
}
return i;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.