Hi all,
Why the following code gives segmentation fault ????
Code:#include<stdio.h>
int main()
{
char *p="hello";
printf("%s",p);
printf("\n%c",*p);
p++;
*p='g';
printf("\n%s",p);
return 0;
}
Printable View
Hi all,
Why the following code gives segmentation fault ????
Code:#include<stdio.h>
int main()
{
char *p="hello";
printf("%s",p);
printf("\n%c",*p);
p++;
*p='g';
printf("\n%s",p);
return 0;
}
You are trying to modify a string literal. You shouldn't try to do that.You can modify six characters there. Five if you want it to remain a string.Code:char p[] ="hello";
Quzah.
This thread goes a little deeper into why you can't do that: http://cboard.cprogramming.com/c-pro...als-store.html
This is also creating problems....
The above code produces the following error...Code:#include<stdio.h>
int main()
{
char p[]="harpreet";
printf("%s",p);
printf("\n%c",*p);
p++;
*p='g';
printf("\n%s",p);
return 0;
}
What is the reason for this ???Code:Test.c: In function ‘main’:
Test.c:8: error: lvalue required as increment operand
please help....
Regards
C_Enthuaist
The reason is that you cannot increment an array. What you can do is to get a pointer to point to the first element of the array, and then increment that pointer.