1
votes

When compiling this program I receive an output that I would've never expected. When I reviewed this program I expected the outcome of pointer to be still "Hello, world!" because to my knowledge pointer was never affected by pointer2. Yet, my output shows that when pointer is printed it contains pointer2's string "y you guys!". How is this so?? Thanks!!

#include <stdio.h>
#include <string.h>

int main() {
    char str_a[20];
    char *pointer;
    char *pointer2;

    strcpy(str_a, "Hello, world!\n");
    pointer = str_a;
    printf(pointer);

    pointer2 = pointer + 2;
    printf(pointer2);
    strcpy(pointer2, "y you guys!\n");
    printf(pointer);
}

Output

Hello, world!
llo, world!
Hey you guys!
1
pointers point to memory addresses. That being said, pointer is pointing to the base address of str_a and pointer2 is pointing 2 bytes ahead of the base address of str_a. So, you are affecting str_a data each time you're accessing any of the pointers. - pah

1 Answers

7
votes

You have a single area of memory, the array str_a.

After strcpy call and the assignments to pointer and pointer2 is looks something like this in memory:

+---+---+---+---+---+---+---+---+---+---+---+---+---+----+----+----------------------+
| H | e | l | l | o | , |   | w | o | r | l | d | ! | \n | \0 | (uninitialized data) |
+---+---+---+---+---+---+---+---+---+---+---+---+---+----+----+----------------------+
^       ^
|       |
|       pointer2
|
pointer

The variable pointer points to str_a[0] and pointer2 points to str_a[2].

When you call strcpy with pointer2 as the destination, you change the memory that pointer2 points to, which is the same array that pointer also points to, just a couple of character further along.