user6055355
user6055355

Reputation:

Confusion with pointer program (c programming)

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!

Upvotes: 1

Views: 55

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409364

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.

Upvotes: 7

Related Questions