views:

135

answers:

5

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.

+4  A: 
scanf('%s', aName);

Use double quotes:

scanf("%s", aName);

Or to be sure:

scanf("%19s", aName);

To limit the string to 19 characters

Maurits Rijk
+9  A: 

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.

Aidan Cully
You should turn on full warnings in whatever compiler you are using (eg -Wall for gcc). It will bring you much in the form of enlightenment. That would have caught this bug, and likely have told you exactly what was wrong.
Tim Schaeffer
+2  A: 

use double quotes in scanf

Neeraj
+3  A: 

Try replacing the scanf line with this:

scanf ("%s", aName);

Note the double quote.

...richie

Richie
A: 

Hello,

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;
}
robUK