user1695758
user1695758

Reputation: 173

Printing Address of Struct Element

I have the following struct:

typedef struct Author
{
    char** novels;
} Author;

And I want to print the address of an element in the novels array. I tried these two:

 printf("%p\n", &(herbert->novels[1]));
 printf("%p\n", herbert->novels[1]);

But I'm not sure which is correct. Can someone help me understand which to use and why?

Upvotes: 0

Views: 992

Answers (1)

NirMH
NirMH

Reputation: 4939

Take a look at the below...

typedef struct Author
{
    char** novels;
} Author;


int main()
{
    Author a;
    char b = 'b';
    a.novels = new char*[2];
    a.novels[0] = NULL;
    a.novels[1] = NULL;

    printf("1. %p\n", a.novels[1]);    
    printf("2. %p\n", &(a.novels[1]));

    delete[] a.novels;
    return 0;
}

this outputs the following

1. 0000000000000000
2. 00000000001269C8

You can see the first print is actually a NULL - which is the value stored at the a.novels[1].

The second is the address of the a.novels[1] memory.

Assuming you look for the memory address of the item, you'll need the second syntax

printf("%p\n", &(herbert->novels[1]));

Upvotes: 1

Related Questions