简体   繁体   English

为什么我不能在C中取消引用指向struct的指针?

[英]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. 我在C中创建了一个结构,并尝试以不同的方式打印结构值。

#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. 以下2个代码无效。

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() . ((char *)pNode + 16)的类型是char * ,所以当你取消引用它时你得到一个char ,它只是在调用printf()时提取LPTSTR指针的第一个字节。 The type of &((*pNode).pData) is *LPTSTR , so when you dererence it you get a LPTSTR , so it passes the complete pointer to printf() . &((*pNode).pData)*LPTSTR ,所以当你取消它时你得到一个LPTSTR ,所以它将完整的指针传递给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. %s期望其参数是指向以null结尾的字符串的指针。 But *((char *)pNode + 16) is just one byte of the pointer, not the whole pointer. *((char *)pNode + 16)只是指针的一个字节,而不是整个指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM