-3

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);
Jorgel
  • 920
  • 3
  • 14
  • 28
  • If they are arrays of pointers you should do (char**) and (XmElem**) in your malloc –  Sep 24 '14 at 15:03
  • 1
    possible duplicate of [Do I cast the result of malloc?](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – ThisaruG Sep 24 '14 at 15:06
  • Didn't know it was bad to cast a malloc, I thought it was the other way around. Thank you – Jorgel Sep 24 '14 at 15:09

1 Answers1

1

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);
Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270