Tutorial :Segmentation fault in equating a char pointer value to some char [duplicate]



Question:

Possible Duplicate:
Why is this C code causing a segmentation fault?

char* string = "abcd";  

now when i try to change some character of this string i get segmentation fault

*string = 'p';  

or

string[0] = 'p';  string[0] = 52;  

Can someone please explain me the reason that why is it happening.

Thanks

Alok.Kr.


Solution:1

If you write char* string = "abcd"; the string "abcd" is stocked into the static data part of your memory and you can't modify it.

And if ou write char* string = 'p';, that's just wrong. First, you try to declare a variable with the same name (string) and, worse, you try to assign a char value to a char pointer variable. This doesn't work. Same thing : char[0] = 'p'; really means nothing to your compiler except a syntax error.


Solution:2

String literals are non-modifiable in C. This has been asked and answered many times before, though it isn't too easy to search for.


Solution:3

If you want to modify string, declare it as an array, not a pointer to a string literal.

#include <stdio.h>    int main()  {      char string[] = "hello world";      string[0] = 'H';      string[6] = 'W';        printf("%s\n", string);        return 0;  }  

Results in:

$ /tmp/hello  Hello World  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »