WeaklyTyped
WeaklyTyped

Reputation: 1341

Why does & operator give different value for struct type

Consider the following test program (codepad execution):

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


struct camp {
    char b[8];
};


int main()
{
    struct camp c;
    strcpy(c.b, "Hello");
    c.b[5] = '\0';
    printf("c size: %d\nAddress (amp): %d :: %d\n", sizeof(c), &c, c);
    printf("Address of b: %d :: %d\n", &(c.b), c.b);

    return 0;
}

A sample output:

c size: 8
Address (amp): -1082463628 :: 1819043144
Address of b: -1082463628 :: -1082463628

Whereas the address given by &(c.b) and c.b (second call to printf) is same, the same for struct camp c (first call to printf) returns different address. Furthermore, &c being same as &(c.b) or c.b.

What exactly is happening?

Upvotes: 0

Views: 113

Answers (2)

Omkant
Omkant

Reputation: 9214

There is only one data member in the struct hence you are seeing the same address for b as well as for c the struct object.

Also array name gives the address of the first element of that array.Hence , c.b will give the same address as &(c.b) since the later one is address of whole array.

&c &(c.b) and c.b will be same in your case but you are printing the c using %d format specifier , so you are seeing an undefined behaviour , The last argument is not the address of c (so you are getting garbage value).

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409364

What printf is trying to do in the first case is to interpret c as an integer. c is not an integer, or even a value that can be converted to an integer (explicitly or implicitly), so the value written can be anything as you are invoking undefined behavior.

Upvotes: 5

Related Questions