2014-09-24 44 views
-3

我有兩個需要分配內存的指針數組,但我在轉換時遇到問題。代碼似乎是工作的罰款,但給我如何從malloc轉換爲指針數組C

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); 
+0

如果他們是指針,你應該數組在你的malloc中執行(char **)和(XmElem **) – 2014-09-24 15:03:35

+1

可能重複[我是否投出malloc?]的結果(http://stackoverflow.com/questions/605845/do-i-cast-the-結果的malloc) – 2014-09-24 15:06:44

+0

不知道它投了一個malloc不好,我認爲這是另一回事。謝謝 – Jorgel 2014-09-24 15:09:42

回答

1

你的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. 
}; 

如何通過malloc轉換爲指針數組用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);