-
December 27th, 2012, 02:01 AM
#1
malloc for union inside structure fails.
Hi Guru's,
I have some problem while allocating memory to a union inside structure. Below is the code i am using
ON SYSTEM1:
This works fine
ON SYSTEM2:
compiler complains saying "need structure or union type" while allocating MYSTRUCT1.
if i change,
shreyas[0].UnionAttr.struct1 = (MYSTRUCT1 *) malloc (sizeof(MYSTRUCT1)
to
shreyas[0].UnionAttr->struct1 = (MYSTRUCT1 *) malloc (sizeof(MYSTRUCT1)
This compiler on SYSTEM2 is happy. but second way does not look correct to me and compiler on system 1 complains about it.
Can someone pls help know which is the correct way to allocate memory?
If first one is correct then what should i look in for to avoid this error?
Could this be an issue with compiler on SYSTEM2?
NOTE: if i use second method on SYSTEM2 code segfaults during malloc.
Please help ASAP, i am stuck because of this for long time.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct mystruct1 {
int a;
int b;
} MYSTRUCT1;
typedef struct mystruct2 {
int a;
int b;
} MYSTRUCT2;
typedef union myunion {
MYSTRUCT1 *struct1;
MYSTRUCT2 *struct2;
} MYUNION;
typedef struct mystruct {
int a;
MYUNION UnionAttr;
} MYSTRUCT;
int main()
{
int flag = 1;
int i;
// Allocate memory
MYSTRUCT *shreyas;
if ((shreyas = (MYSTRUCT *) calloc (2,sizeof(MYSTRUCT))) == NULL)
fprintf(stderr, "Error allocating mystruct\n");
// Allocate to union elements
if ((shreyas[0].UnionAttr.struct1 = (MYSTRUCT1 *) malloc (sizeof(MYSTRUCT1))) == NULL) {
fprintf(stderr, "Error allocating mystruct1\n");
free(shreyas);
}
if ((shreyas[1].UnionAttr.struct2 = (MYSTRUCT2 *) malloc (sizeof(MYSTRUCT2))) == NULL) {
fprintf(stderr, "Error allocating mystruct2\n");
free(shreyas);
}
// Access elements
shreyas[0].UnionAttr.struct1->a = 10;
shreyas[1].UnionAttr.struct2->a = 20;
shreyas[0].UnionAttr.struct1->b = 100;
shreyas[1].UnionAttr.struct2->b = 200;
printf("Struct 1 elements a = %d b = %d\n", shreyas[0].UnionAttr.struct1->a, shreyas[0].UnionAttr.struct1->b);
printf("Struct 2 elements a = %d b = %d\n", shreyas[1].UnionAttr.struct2->a, shreyas[1].UnionAttr.struct2->b);
printf("Success\n");
return;
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|