Reputation: 103
#include <stdio.h>
#include <stdlib.h>
struct integer2{
int* valuePtr;
struct integer2* next;
};
typedef struct integer2* intpointer2;
int main() {
int value2 = 5;
int* dpointer = &value2;
intpointer2 intPtr2 = (intpointer2)malloc(sizeof(struct integer2));
//intPtr2->valuePtr = (int*)malloc(sizeof(int));
printf("Version1\n");
intPtr2->valuePtr = value2; //dereference
printf("intPtr2->valuePtr address %p\n",&intPtr2->valuePtr);
printf("intPtr2->valuePtr value: %d\n", intPtr2->valuePtr);
//print 5
printf("--------------------------------------------\n");
printf("Version2\n");
intPtr2->valuePtr = &value2;
printf("intPtr2->valuePtr address %p\n",&intPtr2->valuePtr);
printf("intPtr2->valuePtr value: %d\n", intPtr2->valuePtr);
printf("intPtr2->valuePtr value: %d\n", (*intPtr2).valuePtr);
//print 1834136
printf("--------------------------------------------\n");
return 0;
}
Hi, i have a question about pointer & dereference
In version#1, when I put intPtr2->valuePtr = value2;
I can print the value of 5
But in version#2, when I put intPtr2->valuePtr = &value2;
I print a weird output like 1834136
isn't valuePtr a pointer? I store the address of value2 should be not problem. and in version#1, I only store the int, but I can print the value of 5. I have no idea about this @@a
and one more question, what is the 1834136? it is an unsigned digits?
thank
Upvotes: 0
Views: 188
Reputation: 38626
You should use version 2. But:
printf("intPtr2->valuePtr address %p\n",&intPtr2->valuePtr);
printf("intPtr2->valuePtr value: %d\n", intPtr2->valuePtr);
The first line should be:
printf("intPtr2->valuePtr address %p\n",intPtr2->valuePtr);
Since valuePtr
is already a pointer as you said, otherwise you're giving it the address of the pointer, which is not what you want. I'm pretty sure you want the address the pointer points to.
The second line should be:
printf("intPtr2->valuePtr value: %d\n", *intPtr2->valuePtr);
Since intPtr2->valuePtr
is the pointer itself, but you still have to dereference it to get the actual int. Doing (*intPtr2).valuePtr
is exactly what intPtr2->valuePtr
does, ->
is short-hand for that syntax, so you'd still be left with the valuePtr
pointer and would still have to dereference it.
Example: http://ideone.com/Fh8wwr
Upvotes: 1