简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM