I have written this simple program to print a string in reverse order but it is showing segmentation fault.
#include<stdio.h>
#include<string.h>
int main (int argc, char **argv)
{
char *string;
int n;
printf("Enter a string\n");
scanf("%s",string);
printf("\n");
n = strlen(string);
printf("%d",n);
while(n != 0)
{
printf("%c",string[n]);
n--;
}
return(0);
}
Can anybody explain me why I am getting this segmentation fault? Opearating system : Ubuntu , compilor : gcc
char *stringcreates a variable which can hold a pointer to a string, but it is not set here. So it points to a random location which, when accessed, segfaults.To be useful, either allocate some memory and assign that to the pointer:
or, do it all at once:
Ideally, instead of using a hardcoded constant (like my example
1000) use a symbolic constant, or better yet, find out how long the string needs to be and then use that.