gpt4 book ai didi

c - 如何在 C 中从 malloc 转换为指针数组

转载 作者:行者123 更新时间:2023-11-30 21:03:17 25 4
gpt4 key购买 nike

我有两个指针数组,需要为其分配内存,但在转换它们时遇到问题。该代码似乎工作正常,但给了我

warning: assignment from incompatible pointer type [enabled by default]

这些是类型和 malloc 代码:

typedef struct Elem Elem;
struct Elem {
char *(*attrib)[][2]; //type from a struct
Elem *(*subelem)[]; //type from a struct
}

Elem *newNode;

newNode->attrib = (char*)malloc(sizeof(char*) * 2 * attrCounter);
newNode->subelem = (Elem*)malloc(sizeof(Elem*) * nchild);

最佳答案

你对struct Elem的定义看起来很奇怪。

struct Elem {
char *(*attrib)[][2]; // attrib points to an array of unknown size.
Elem *(*subelem)[]; // Same here. subelem points to an array of unknown size.
};

也许您想使用:

struct Elem {
char *(*attrib)[2]; // attrib points to an array of 2 pointers to char.
Elem *subelem; // subelem points to an sub Elems.
};

How to cast from malloc to array of pointers in C

简单的解决方案 - 不要转换 malloc 的返回值。众所周知,它会引起问题。请参阅Specifically, what's dangerous about casting the result of malloc?了解详情。只需使用:

newNode->attrib = malloc(sizeof(char*) * 2 * attrCounter);   
newNode->subelem = malloc(sizeof(Elem*) * nchild);

您可以使用以下模式使事情变得更简单:

pointer = malloc(sizeof(*pointer)); // For one object.
pointer = malloc(sizeof(*pointer)*arraySize); // For an array of objects.

根据您的情况,您可以使用:

newNode->attrib = malloc(sizeof(*newNode->attrib) * attrCounter);   
newNode->subelem = malloc(sizeof(*newNode->subelem) * nchild);

关于c - 如何在 C 中从 malloc 转换为指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26020160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com