samanta samanta - 6 months ago 16
C Question

Why can't i dereference a pointer to struct in C?

I have created one struct in C and trying to print the struct values in different ways.


#define KEY_SIZE 8
typedef struct _TREENODE {
struct _TREENODE *Left, *Right;

#define NODE_SIZE sizeof(TREENODE)

int _tmain(int argc, LPTSTR argv[])

TCHAR name[]="sachin tendulkar";

pNode = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, NODE_SIZE);

pNode->pData = name;

// Bothe address are same
printf("0x%p = 0x%p\n", ((char *)pNode + 16), (&((*pNode).pData)) );

//Why does it give different value ???
printf("0x%p = 0x%p\n", *((char *)pNode + 16), *(&((*pNode).pData)) );

// ERROR !!!
printf("0x%s = 0x%s\n", *((char *)pNode + 16), *(&((*pNode).pData)) );

return 0;

Below 2 codes are not working.

printf("0x%p = 0x%p\n", *((char *)pNode + 16), *(&((*pNode).pData)) );

printf("0x%s = 0x%s\n", *((char *)pNode + 16), *(&((*pNode).pData)) );

Both the below code are giving same output:

((char *)pNode + 16) = (&((*pNode).pData))

But below codes are not!

*((char *)pNode + 16) != *(&((*pNode).pData))

//Why does it give different value ???
printf("0x%p =  0x%p\n", *((char *)pNode + 16), *(&((*pNode).pData))  );

The addresses are the same, but the types aren't. The type of ((char *)pNode + 16) is char *, so when you dereference it you get a char, and it just extracts the first byte of the LPTSTR pointer when it calls printf(). The type of &((*pNode).pData) is *LPTSTR, so when you dererence it you get a LPTSTR, so it passes the complete pointer to printf().

// ERROR !!!
printf("0x%s =  0x%s\n", *((char *)pNode + 16), *(&((*pNode).pData))  );

This is the same problem. %s expects its argument to be a pointer to a null-terminated string. But *((char *)pNode + 16) is just one byte of the pointer, not the whole pointer.