我有两个指针数组需要为其分配内存,但在强制转换它们时遇到了问题。代码似乎运行良好,但给了我
warning: assignment from incompatible pointer type [enabled by default]
这些是类型和mallocs代码:
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.
};
如何在C 中从malloc转换为指针数组
简单的解决方案-不要强制转换malloc
的返回值。众所周知,它会引发问题。请参阅具体内容';铸造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);