samanta
samanta

Reputation: 35

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.

#include<stdio.h>
#include<windows.h>
#include<tchar.h>


#define KEY_SIZE 8
typedef struct _TREENODE {
    struct _TREENODE *Left, *Right;
    TCHAR key[KEY_SIZE];
    LPTSTR pData;
}TREENODE, *LPTNODE, **LPPTNODE;

#define NODE_SIZE sizeof(TREENODE)

int _tmain(int argc, LPTSTR argv[])

{
    LPTNODE pNode;
    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))

Upvotes: 1

Views: 171

Answers (1)

Barmar
Barmar

Reputation: 781834

//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.

Upvotes: 3

Related Questions