nagaharikola
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.
int main() {
char *buffer;
printf("etner a string");
gets(buffer);
printf("%s", buffer);
return 0;
}
getting segmentation fault
how to correct this.
char buffer[50]
ASKER
I don't want to declare arrays.
i want to declare a char pointer and run the program
i want to declare a char pointer and run the program
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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?
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.
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.