The following program is throwing segmentation fault.
#include<stdio.h>
int main(){
char *p = "exs";
char x;
x = (*p)++;
printf("%c\n",x);
return(0);
}
Please help.
I was expecting 'f' but got seg fault.
The following program is throwing segmentation fault.
#include<stdio.h>
int main(){
char *p = "exs";
char x;
x = (*p)++;
printf("%c\n",x);
return(0);
}
Please help.
I was expecting 'f' but got seg fault.
You need to copy the string into writeable memory first using strdup. Then use ++(*p) instead of (*p)++ to get the value after incrementing the first byte. Although not necessary in short-lived processes, it is a good style to free() the memory allocated with strcpy() when it is not used to avoid memory leaks.
With these changes applied, the program would look like this:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char *p = strdup("exs");
char x;
x = ++(*p);
printf("%c\n",x);
free(p);
return(0);
}