[英]Want to access struct pointer's data of type from struct's memory in C
My program dynamically allocates nodes of type struct pointer. 我的程序动态分配结构指针类型的节点。 I want to access the data of struct pointer via it's memory address. 我想通过它的内存地址访问struct指针的数据。 The main purpose of my question is to test b-tree insert with split. 我的问题的主要目的是测试带有拆分的b树插入。 Here is the struct: 这是结构:
struct LeafNode
{
int EmpID[M];
int Location[M];
int keys;
};
typedef struct LeafNode* LNodePtr;
Here is my test code: 这是我的测试代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int * a = (int *)malloc(sizeof(int));
*a = 5;
printf("int a created at %p\n", (void *) &a);
void * addr;
printf("Give the memory address: ");
scanf("%p", addr);
void * addr2 = (void *)addr;
printf("The value at memory is: %d\n",*(int*)addr2);
return 0;
}
Here' s the result: 结果如下:
int a created at 0xbff573b4 int创建于0xbff573b4
Give the memory address: 0xbff583b4 给出内存地址:0xbff583b4
Segmentation fault 分段故障
The second step is to cast to LNodePtr instead of int. 第二步是强制转换为LNodePtr而不是int。 I don't know if we can use double cast, ie 我不知道我们是否可以使用双重转换
*(int *(LNodePtr))addr
so that i can access 这样我就可以访问
struct's EmpID[0]
int
member through memory. int
成员通过内存。 Thanks for help. 感谢帮助。
void * addr;
Allocates a pointer, but does not initialize it. 分配一个指针,但不初始化它。
scanf("%p", addr);
Reads a pointer into the variable stored at the address held in addr
. 将指针读入存储在addr
保存的地址的变量中。 You did not initialize addr
so this is undefined behaviour. 您没有初始化addr
所以这是未定义的行为。
Perhaps you meant to write: 也许您打算写:
scanf("%p", &addr);
But it's very hard to tell. 但这很难说。 Not least because you talk at length about a struct
and then have code that does not mention the struct and instead works with void*
. 尤其重要的是,因为您详细讨论了一个struct
,然后有了不提及该结构的代码,而是使用了void*
。
printf("int a created at %p\n", (void *) &a);
This prints the address of the variable holding the pointer a
. 这将打印保存指针a
的变量的地址。 If you want to print the value of the pointer, use a
instead of &a
. 如果要打印指针的值,请使用a
代替&a
。
You shouldn't dereference a in your printf line, a itself is already a pointer, *a is the int! 您不应该在printf行中取消引用a,它本身已经是一个指针,* a是int!
printf("int a created at %p\n", (void *) a);
Also, you should dereference the void* in scanf 另外,您应该在scanf中取消引用void *
scanf("%p", &addr);
As a general tip, try compiling with the C flag -Wall, so you can easily catch these mistakes. 作为一般提示,请尝试使用C标志-Wall进行编译,这样您就可以轻松捕获这些错误。
To answer the question in the comments, in case you have the node address 0x1234, you could do this: 要回答注释中的问题,如果节点地址为0x1234,则可以执行以下操作:
MyNode *node = 0x1234;
node->int[0] = 5;
Hope that answers the question 希望能回答这个问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.