Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - I'm getting two diferents pointers from the same variable

Tags:

c

pointers

Context

I was studing about pointer in C, for that I was testing some pointer's algorithm and in one of this tries I make a little change that is bugging until now.

This is the code:

char *s = "ABCDEF";
char **y = &s;

printf("%p\n", s);
printf("%p\n", &s);

printf("%p\n", y);
printf("%p\n", &s[0]);

The problem is that for some reason when I ask for C to print the pointer of S (without the ampersand), I receive one pointer, but when I put the ampersand I receive another pointer differently. I think that this didn't happen because the ampersand will give me the address of S.

So to check if isn't a bug, I make a pointer with the address of S, and I received the same that the "&s" as expected, but when I use the "&s[0]" I received the value of the single "s".

So, why is C giving me two results if in both cases I'm just asking for the first character of the string?

The values that I received

0x400634
ox7ffd95c33090
ox7ffd95c33090
0x400634

I know that probably I'm forgetting some piece of logic, but I've struggled with this, so if someone can help me, I'll appreciate it.

like image 395
Will Felipe Avatar asked Aug 30 '21 16:08

Will Felipe


1 Answers

The variable s stores the address of the string literal "ABDCDEF"; the variable y stores the address of the variable s.

    char **        char *        char
    +---+          +---+         +---+
 y: |   | ----> s: |   | ------> |'A'|
    +---+          +---+         +---+
                                 |'B'|
                                 +---+
                                 |'C'|
                                 +---+
                                 |'D'|
                                 +---+
                                 |'E'|
                                 +---+
                                 |'F'|
                                 +---+
                                 | 0 |
                                 +---+  
like image 142
John Bode Avatar answered Nov 03 '22 00:11

John Bode