Gonzo
Gonzo

Reputation: 1553

Edit an array of char*

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?

Upvotes: 0

Views: 351

Answers (5)

P.P
P.P

Reputation: 121397

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.

Upvotes: 3

pb2q
pb2q

Reputation: 59617

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].

Upvotes: 4

Alex Reynolds
Alex Reynolds

Reputation: 96967

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.

Upvotes: 1

Seva Alekseyev
Seva Alekseyev

Reputation: 61378

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"; 

Upvotes: 0

mathematician1975
mathematician1975

Reputation: 21351

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

Upvotes: 0

Related Questions