我现在正在学习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()接受字符串第一个参数,因此需要双引号。

10-07 19:11
查看更多