Wednesday, 7 June 2017

How to cast from malloc to array of pointers in C




I have two arrays of pointers that I need to allocate memory to, but I am having problems when casting them. The code seems to be working fine, but is giving me



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


These are the types and mallocs codes:



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

Answer



Your definition of struct Elem seems strange.




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


Perhaps you meant to use:



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




Simple solution - don't cast the return value of malloc. It's known to cause problems. See Specifically, what's dangerous about casting the result of malloc? for details. Just use:




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


You can use the following pattern to make things simpler:



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



In your case, you can use:



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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...