C - 调用 scanf() 时出现程序段错误
我现在正在学习 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;
}
编辑:我忘了提及,它甚至没有显示提示或让我输入名称。执行后立即崩溃。
I'm learning C right now, and I copied this little snippet straight from the book I'm using. It segfaults when I run it and I can't figure out why, I ran it through gdb and it stops at line 9 scanf("%s", aName);, but printing the values of the variables brings up nothing suspicious looking. What's wrong with this thing?
#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;
}
edit: I forgot to mention, it didn't even display the prompt or let me enter a name. it crashed immediately after executing it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在清单中,您有
'%s'
而不是"%s"
- 请注意单引号和双引号之间的差异。单引号分隔字符,双引号分隔字符串。scanf()
第一个参数采用字符串,因此需要双引号。In the listing, you have
'%s'
instead of"%s"
- note the diff between single and double quotes. Single quotes delimit characters, double quotes delimit strings.scanf()
takes a string first argument, so you need double quotes.使用双引号:
或者确定:
将字符串限制为 19 个字符
Use double quotes:
Or to be sure:
To limit the string to 19 characters
尝试用以下内容替换 scanf 行:
注意双引号。
...里奇
Try replacing the scanf line with this:
Note the double quote.
...richie
在 scanf 中使用双引号
use double quotes in scanf
如果这是一个计算字母数量的练习,那么您可以执行以下操作,但使用指针。
If this is an exercise to count the number of letters then you could do the following, but using pointers.