简体   繁体   中英

C - Program segfaulting when scanf() is called

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.

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.

scanf('%s', aName);

Use double quotes:

scanf("%s", aName);

Or to be sure:

scanf("%19s", aName);

To limit the string to 19 characters

Try replacing the scanf line with this:

scanf ("%s", aName);

Note the double quote.

...richie

在scanf中使用双引号

If this is an exercise to count the number of letters then you could do the following, but using pointers.

int nameLength(char *name)
{
    int i = 0;
    while(*name++) {
        i++;
    }
    return i;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM