jTruBela
jTruBela

Reputation: 75

Error Using pointers to get memory address locations

I have since figured this out. Thank you...I'm new to C and having trouble getting the memory address of the variable that's assigned to the pointer.

What am I missing or not understanding here. The valueVariable needs to be declared. The pointerVariable needs to be declared and set to the &valueVariable. still unsure what %x does to be honest. TIA

int main () {

    double innerD, outerD, density, thickness;
    double *innerDPointer, *outerDPointer, *thicknessPointer, *densityPointer;

    innerD = 0.0;
    outerD = 0.0;
    density = 0.0;
    thickness = 0.0;

    innerDPointer = &innerD;
    outerDPointer = &outerD;
    densityPointer = &density;
    thicknessPointer = &thickness;

    int quantity;
    int *quantityPointer;

    quantityPointer = &quantity;

    printf("\nAddress of innerD variable: %x\n", &innerD);
    printf("\nAddress of outerD variable: %x\n", &outerD);
    printf("\nAddress of density variable: %x\n", &density);
    printf("\nAddress of thickness variable: %x\n", &thickness);
    printf("\nAddress of quantity variable: %x\n", &quantity);

    return 0;
}

Upvotes: 0

Views: 70

Answers (1)

Amoz PAY
Amoz PAY

Reputation: 26

In order to access a variable's address, you use the & operator in front of the variable. Thus, when you use printf with &innerD as a second parameter, you are telling printf to print your line and to replace %x with a hexadecimal value, which is &innerD. Typically, to print an adress, you would use the %p format. The %x is meant to print an unsigned int in hexadecimal form, and that's why you have a warning, because you're passing an double *, and not an unsigned int

That being said, note that not at any moment you have to use a new int * variable since you directly passed the variable address to printf.

int main()
{
    double innerD, outerD, density, thickness;

    innerD = 0.0;
    outerD = 0.0;
    density = 0.0;
    thickness = 0.0;

    int quantity;

    printf("\nAddress of innerD variable: %p\n", &innerD);
    printf("\nAddress of outerD variable: %p\n", &outerD);
    printf("\nAddress of density variable: %p\n", &density);
    printf("\nAddress of thickness variable: %p\n", &thickness);
    printf("\nAddress of quantity variable: %p\n", &quantity);

    return 0;
}

to find more details on how to use printf flags, enter the command man 3 printf in your terminal, if you use a unix system (mac or linux)

Upvotes: 1

Related Questions