how to allocate memory to a member at run time

R

raghu

Hello ,

This is Raghu. I have a problem in declaring a structure.
Consider
struct hai{
int id;
char sex;
int age;
};
here when a variable is instianted for this structure then immediately
for all members memory is allocated. But I need to allocate memory for
age only if sex is M else the memory should not allocate.
Think you understand the query.

awaiting for your reply
bye take care
with smile
Raghu
 
T

thunder1

struct hai
{
int id;
char info[1];
}
If sex is M then p = (struct hai*)malloc(sizeof(struct hai)+1).
p->info[0] value is M,and p->info[1] is age.
If sex is F then p= (struct hai*)malloc(sizeof(struct hai)).p->info[0]
value is F.
raghu 写é“:
 
C

Christopher Benson-Manica

struct hai
{
int id;
char info[1];
}
If sex is M then p = (struct hai*)malloc(sizeof(struct hai)+1).
p->info[0] value is M,and p->info[1] is age.
If sex is F then p= (struct hai*)malloc(sizeof(struct hai)).p->info[0]
value is F.

1. Don't cast the return value of malloc(). Search this group's
archives and the FAQ.

2. OP stated that age is an int, not a char:

The struct hack is really not particularly helpful in OP's situation
anyway.
 
A

Andrew Poelstra

Hello ,

This is Raghu. I have a problem in declaring a structure.
Consider
struct hai{
int id;
char sex;
int age;
};
here when a variable is instianted for this structure then immediately
for all members memory is allocated. But I need to allocate memory for
age only if sex is M else the memory should not allocate.
Think you understand the query.

struct hai
{
int id;
char info[1];
}
If sex is M then p = (struct hai*)malloc(sizeof(struct hai)+1).
p->info[0] value is M,and p->info[1] is age.
If sex is F then p= (struct hai*)malloc(sizeof(struct hai)).p->info[0]
value is F.

Firstly, snip signatures and don't top-post.
Secondly, write your malloc()'s more robustly:

p = malloc(sizeof *p + 1);
p = malloc(sizeof *p);
 
C

CBFalconer

Andrew said:
.... snip ...

Firstly, snip signatures and don't top-post.
Secondly, write your malloc()'s more robustly:

p = malloc(sizeof *p + 1);
p = malloc(sizeof *p);

Clearer is:

p = malloc(1 + sizeof *p)

which makes it absolutely clear that sizeof operates on *p alone.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,438
Messages
2,571,699
Members
48,796
Latest member
Greg L.
Top