user6122015
user6122015

Reputation:

What address is this pointer assignment returning?

I was playing around with pointers the other day and came up with the following code where I explicitly cast an int variable to int * and print out the address of the explicitly casted variable

#include <stdio.h>

int main (void)
{
    int d;
    int *p1, *p2;

    printf("%p\n", p1 = &d);
    printf("%p\n", p2 = (int *) d);

    return 0;
}

Here's the output:

ffbff71c
ffbff878

My question is what is that second address and what is contained there?

Upvotes: 0

Views: 46

Answers (4)

John Bollinger
John Bollinger

Reputation: 181469

As others have pointed out, you are converting an indeterminate value to a pointer. Performing that conversion, or indeed doing anything with that value other than overwriting it, produces undefined behavior.

If d's value were set prior to the conversion, then it would matter that C explicitly permits integers to be converted to pointers. However, for this case and most others, the standard says:

the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

[C2011, 6.3.2.3/5]

So basically, don't do that unless you know enough to determine reliably for yourself what the result will be with your particular combination of code, C implementation, compile and link options, and platform.

Upvotes: 0

dimG
dimG

Reputation: 11

It is just a random address in memory since d is not initialized.

Upvotes: 1

Bogdan Alexandru
Bogdan Alexandru

Reputation: 5552

In the second print, you are not printing an address, but a value converted to an address!

In the first assignment, you're taking the address of the variable, which is just some RAM address. In the second assignment, you're converting the variable's value to a pointer. Since the variable is not initialized, that's the garbage value located at that RAM address.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 225172

Garbage - you're printing out the value of an uninitialized variable. It's just total coincidence that it looks like your other address; initialize d to get a meaningful answer.

Upvotes: 5

Related Questions