1

If I declare an array of pointers like that:

    char* arr[5] = {"Mercury",
    "Mercury",
    "Venus",
    "Earth",
    "EArth"};

Can I then change sings in those pointers? I have tried doing something like that

*(*(arr + 1) + 1) = 'i';

but it doesn't work, I get memory dump. Is there a way to do that or I have to declare it differently?

6
  • Things such as "Mercury" are string literals. Trying to modify a string literal results in undefined behaviour, most of the time a seg fault. Commented Apr 28, 2020 at 13:41
  • Each of the 5 pointers in the array points to a string literal. These are constant data, and cannot be changed. Commented Apr 28, 2020 at 13:41
  • String literals in C are usually stored in read-only memory. If you allocate read-write memory, either on the stack by declaring an array, or on the heap with malloc, you will be able to modify the strings. Commented Apr 28, 2020 at 13:41
  • 1
    OT: *(*(arr + 1) + 1) = 'i';--> arr[1][1] = 'i'; but it is still illegal code Commented Apr 28, 2020 at 13:55
  • 1
    You CAN swap pointers, e.g. char *tmp = arr[2]; arr[2] = arr[0]; arr[0] = tmp; would be fine. That would result in the ordering "Venus", "Mars", "Mercury", "Earth", "Pluto" Commented Apr 28, 2020 at 14:04

1 Answer 1

1

Is there a way to do that or I have to declare it differently?

char* arr[5] = {"Mercury", "Mars", "Venus", "Earth", "Pluto"};

arr is an array of 5 char pointers to string literals. Any attempt to modify a string literal invokes undefined behavior, so you can´t modify them.

If you want to modify the content you need f.e. to define them as two-dimensional array of chars:

char arr[5][10] = {{"Mercury"}, {"Mars"}, {"Venus"}, {"Earth"}, {"Pluto"}};

and use

strcpy(arr[0], "Uranus");

size_t len = strlen(arr[0]);  
for(size_t i = 9; i > (len + 1); i--)  // To remove all left characters from prev. string.
{
    a[0][i] = '\0';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.