Surely there is a good explanation somewhere, but I will write my own.
In C/C++ (and pretty much every other language) an array is just a pointer to the first element in the array.
In C/C++ it also allocates memory on the stack, rather than you allocating memory with
new
, but that isn't really important to how they work.
So, we have 3 arrays (pointers)
buf1
,
buf2
and
buf3
.
Each of these is just a pointer to a peice of memory, for this example:
buf1=0x1000
buf2=0x1100
buf3=0x1200
Then the contents of memory starting at 0x1000 is the elements of the array, say for example you have the code:
char buf1[50] = "Hello";
char buf2[50] = "World";
char buf3[50] = "Array";
Then the memory would look like this:
Offset 0x1000:
'H', 'e', 'l', 'l', 'o', '\0', (rest of 50 chars in undefined)
Offset 0x1100:
'W', 'o', 'r', 'l', 'd', '\0', (rest of 50 chars in undefined)
Offset 0x1200:
'A', 'r', 'r', 'a', 'y', '\0', (rest of 50 chars in undefined)
Where each character is 1 byte.
When you pass this pointer into a function, it just passes a copy of the memory location, for example:
void Print(char *str) {
printf(str);
}
int main() {
char buf1[50] = "Hello";
char buf2[50] = "World";
char buf3[50] = "Array";
Print(buf1);
}
Then what happens is the pointer to buf1 is passed to
Print()
, which is the memory location 0x1000.
This does not create a copy of the memory, and so if the function
Print()
changes anything in the memory, it will affect the string in both
Print()
and
main()
.
If nothing is changed in
Print()
, in this example there isn't, then there is no need to copy the memory.
If you change something and you want this change to go back to the calling function
main()
(such as convert to upper case) you MUST NOT copy the memory (unless you want a copy in the original case as well).
If something is changed in
Print()
and you DON'T want this to change the array in
main()
then you need to copy the array, this can be done with another buffer or some allocated memory:
char buf1[50] = "Hello";
char buf1Copy[50];
strcpy(buf1Copy, buf1);
memcpy(buf1Copy, buf1, sizeof(buf1));