Link to home
Start Free TrialLog in
Avatar of nagaharikola
nagaharikolaFlag for Afghanistan

asked on

segmetnation fault

#include<stdio.h>

int main() {


 char *buffer;
printf("etner a string");
gets(buffer);
 printf("%s", buffer);
 return 0;
}

getting segmentation fault

how to correct this.
Avatar of rysic
rysic
Flag of Poland image

char buffer[50]
Avatar of nagaharikola

ASKER

I don't want to declare arrays.
i want to declare  a char pointer and run the program
ASKER CERTIFIED SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
char *buffer only declares a pointer to a character buffer, it does not declare or reserve and space in memory in which a character string can be stored.

The description of gets shows:

      gets()         Reads characters from the standard input stream, stdin,
                     into the array pointed to by s, until a new-line
                     character is read or an end-of-file condition is
                     encountered.  The new-line character is discarded and
                     the string is terminated with a null character.

Notice how it says "into the array pointed to by s".  You aren't declaring an array and so there is nowhere for gets to store the string that it processes.

Why don't you want to declare an array?
>> char *buffer only declares a pointer to a character buffer
Sorry to be pedantic but actually, it declares a pointer than can point to char. Whether this has 'buffer' (or string) semantics or not is down to how this pointer is interpreted.