-3

Recently i have started working on built-in functions but came up with an error and that is:

Why am i getting segmentation fault for this program

#include<stdio.h>
#include<ctype.h>
int main()
{
    char str[50];
    int n;
    printf("Who is your best friend? ");
    scanf("%s",str);
    n=isalpha(str);
    if(n!=0)
    {
        printf("Is Alpha");
    }
    else
    {
        printf("Invalid Input");
    }
    return 0;
}

Please help me out...

  • Compile your code with all warnings and debug info: `gcc -Wall -Wextra -g` with [GCC](http://gcc.gnu.org/). Improve your code to get no warnings. Then [use the `gdb` debugger](https://sourceware.org/gdb/current/onlinedocs/gdb/) – Basile Starynkevitch Mar 07 '18 at 12:55
  • Also read the [documentation](http://en.cppreference.com/w/c), notably of each function you are using (because you use them wrongly) – Basile Starynkevitch Mar 07 '18 at 12:57
  • 5
    For a start: `isalpha` takes a `char` as a parameter not an array of `char`s. Also this code has nothing to do with recursion. – mttrb Mar 07 '18 at 12:57

1 Answers1

4

isalpha()'s prototype is

int isalpha( int ch );

The argument is of type int. But the one that you are passing is of type char * since str is a character array.

Perhaps you meant

unsigned char str;
scanf("%c",&str);

isalpha() returns 0 if its argument is not alphabetic.

And to avoid overflow, you could modify your scanf() to

scanf("%49s",str);

with one character to store the \0 character.

Have a look at this post.

Edit: The argument of isalpha() shouldn't be char. It must be at least unsigned char as explained here. Thanks to melpomene for pointing this out.

J...S
  • 5,079
  • 1
  • 20
  • 35