Home > Mobile >  Does changing an array copy data?
Does changing an array copy data?

Time:10-04

If I defined a global array of strings like:

char* arr[] = {
    "abc",
    "def",
    "gh",
    NULL
};

and then I tried to change the first element in the main() function like:

arr[0]="something"

Does changing elements of an array copy data? Did this make a copy of the original arr[0] or?

CodePudding user response:

Elements of arr contain pointers to cstrings as arr is declared to be an array of pointers to char. The elements themselves do not actually contain the cstrings.

So, when you do arr[0] = "something", the data stored at arr[0] is overwritten with the address of something. At this point, there is one instance each of abc and something, but, you can't reach abc using arr[0] any more.

CodePudding user response:

It's basically equivalent to this:

char* arr[4];

arr[0] = "abc";
arr[1] = "def",
arr[2] = "gh",
arr[3] = NULL;

arr[0] = "something";

The original string "abc" is left untouched, but also inaccessible, unless you save a pointer to it. So this:

arr[0] = "abc";
char *s = arr[0];
arr[0] = "something";
puts(s);

will print "abc";

  • Related