Is it possible to modify a string of char in C?

2018-12-31 15:13发布

I have been struggling for a few hours with all sorts of C tutorials and books related to pointers but what I really want to know is if it's possible to change a char pointer once it's been created.

This is what I have tried:

char *a = "This is a string";
char *b = "new string";

a[2] = b[1]; // Causes a segment fault

*b[2] = b[1]; // This almost seems like it would work but the compiler throws an error.

So is there any way to change the values inside the strings rather than the pointer addresses?

Thanks

EDIT:

Thanks everyone for your answers. It makes more sense now. It especially makes sense why sometimes it was working fine and other times not working. Because sometimes I'd pass a char pointer and other times a char array (the char array worked fine).

9条回答
临风纵饮
2楼-- · 2018-12-31 15:38

The memory for a & b is not allocated by you. The compiler is free to choose a read-only memory location to store the characters. So if you try to change it may result in seg fault. So I suggest you to create a character array yourself. Something like: char a[10]; strcpy(a, "Hello");

查看更多
人气声优
3楼-- · 2018-12-31 15:40

No, you cannot modify it, as the string can be stored in read-only memory. If you want to modify it, you can use an array instead e.g.

char a[] = "This is a string";

Or alternately, you could allocate memory using malloc e.g.

char *a = malloc(100);
strcpy(a, "This is a string");
free(a); // deallocate memory once you've done
查看更多
呛了眼睛熬了心
4楼-- · 2018-12-31 15:40

You could also use strdup:

   The strdup() function returns a pointer to a new string which is a duplicate of the string  s.
   Memory for the new string is obtained with malloc(3), and can be freed with free(3).

For you example:

char *a = strdup("stack overflow");
查看更多
登录 后发表回答