[英]Having trouble allocating memory for my double pointer in structure
我正在尝试为指针分配内存,但是引用了该指针的地址。 我还是C的新手,这是我第一次真正使用双指针。 所以我有两个结构,它们看起来像这样:
typedef struct myNodes {
int data;
struct myNodes *next;
} listElement;
typedef struct {
listElement **ptrToElements;
} myStruct;
在另一个文件中,我正在尝试通过执行以下操作为我的指针动态分配内存:
myStruct *myStruct = malloc(sizeof(*myStruct));
*(myStruct->ptrToElements) = (listElement*)malloc(sizeof(listElement));
但是我这样做会遇到分段错误。 可能是什么问题? 谢谢!
问题在于
*(myStruct->ptrToElements) ....
声明。 在取消引用myStruct->ptrToElements
之前,您需要确保它指向有效的内存。
详细说明,您为myStruct
分配内存。 精细。
这构成了为成员ptrToElements
分配内存。 好。
问题: ptrToElements
指出了什么?
答案:不确定性。
因此,当您尝试降低指向不确定内存地址的指针时,它几乎是无效的内存地址,并且尝试这样做会调用未定义的行为。
解决方案 :您需要为myStruct->ptrToElements
分配内存,然后才能继续取消引用它。
话虽如此,请看看我是否投出了malloc的结果?
我想这就是你想要的:
typedef struct myNodes {
int data;
struct myNodes *next; // not clear what this pointer is used for...
} listElement;
typedef struct {
listElement *ptrToElements;
} myStruct;
// Memory Allocation
// allocate myStruct pointing to an array of N listElements
myStruct *ms = malloc(sizeof(myStruct));
ms->ptrToElements = malloc(N * sizeof(listElement));
// element access
for (int i = 0; i < N; i++) {
listElement *le = ms->ptrToElements[i];
le->data = ...
le->next = NULL; // not clear what this pointer is used for...
}
// Memory deallocation
free(ms->ptrToElements);
free(ms);
您可以定义结构以包含指向listElement
指针的指针
typedef struct {
listElement **ptrToElements;
} myStruct;
正如Sourav Ghosh写的那样,你试图为ptrToElements
指向的指针ptrToElements
,而不分配内存。
您可能应该将指针类型更改为
typedef struct {
listElement *ptrToElements;
} myStruct;
并在分配内存时
myStruct *myStruct = malloc(sizeof(*myStruct));
/* If the list can be empty, initialize root with NULL pointer */
myStruct->ptrToElements = NULL;
/* when you add the first list element */
myStruct->ptrToElements = malloc(sizeof(listElement));
myStruct->ptrToElements->data = someValue;
/* at least for the last element you add here you should initialize next */
myStruct->ptrToElements->next = NULL;
不要忘记处理错误,例如malloc返回NULL
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.