Edit an array of char*

2019-08-16 19:25发布

问题:

I have an array of char * like this:

char * gradient_xpm[] = {"abc", "def", "ghi"};

I need to change the value of those strings.

I've tried strcpy and the = operator, but it gives me a Segmentation Fault.

e.g:

strcpy(gradient_xpm[1],"jkl");
gradient_xpm[1][2] = 'x';

I wasn't able to edit even a single char. How can I edit those values?

回答1:

You have string constants in your array, and those can't be changed. This is the cause of your segfaults.

You'll need to setup your array without using string constants, then copy the string constants into your array.

Something like:

char *gradient_xpm[3];

gradient_xpm[1] = (char *) malloc(sizeof(char) * (MAX_STR_LEN + 1));
strncpy(gradient_xpm, "jkl", MAX_STR_LEN);

// now this will work:
gradient_xpm[1][2] = 'x';

Similarly for gradient_xpm[0], gradient_xpm[2].



回答2:

Modifying string literals in C is undefined behavior. So anything can happen, not necessarily a segfault.

From the C99 standard, 6.4.5 String literals 6.4.5/6:

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.



回答3:

You can't modify string constants, which are marked as off-limits. You can, however, modify memory you've allocated on the heap or stack. That said, if you're using C++, consider using arrays of the string class, instead of managing char * arrays. The memory management issues are much easier to handle.



回答4:

You have implemented this using string literals and you cant change them



回答5:

Don't edit the contents - that's a bad, BAD idea. In some compilers, that'd be a compile-time error, as string constants are const char *, as opposed to char*.

Instead, flip the pointer:

gradient_xpm[1] = "jkl"; 


标签: c string char