473,786 Members | 2,304 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to allocate memory to a member dynamically

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.
and awaiting for your reply
bye take care
with smile
Raghu

Oct 24 '06
14 2642
On Tue, 2006-10-24 at 04:21 -0700, raghu wrote:
<formalities snipped>
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.
<formalities snipped>

There's no way to do this. You could pull it off using pointers, but
then you'd still have to allocate memory for the pointers itself
(which, chances are, is just as large as an int would be).

If you really need to do this, you should create separate structs
for men and women. In an OO language, you could do this a little
more elegantly than in C.

--
Andrew Poelstra <http://www.wpsoftware. net/projects/>

Oct 24 '06 #11
On Tue, 2006-10-24 at 07:04 -0700, Ancient_Hacker wrote:
Well, it's hardly worth the effort. If you're allocating with
malloc() there's typically a minium allocation of 8 to 16 bytes, so
saving the "age" field isn much of a savings. In fact often no savings
at all, if malloc does 16-byte alignment for speed.

Also, most people don't live more than 127 years, so you could store
the gender and age in one byte. Either with a union, or by some
convention, such as a signed char where -1 implies female, positive
implies male and gives their age.
Remember to quote context. Yours seems to be the cleverest solution to
the OP's problem, but few can remember what that problem was!

(It was, essentially, "can I only allocate the .age member of a struct
if the .sex member is 'M'"?)
--
Andrew Poelstra <http://www.wpsoftware. net/projects/>

Oct 24 '06 #12
"Ancient_Hacker " <gr**@comcast.n etwrites:
What you're trying to do can be expressed in better-thought-out
languages such as Pascal, which have the concept of a "variant record",
your structure would look like:

hai = record
id: integer;
case
sex: boolean of
true: ( age: integer );
false: ( );
end;

But in C you don't have that option.
The "case" doesn't do anything in your example. It's "the same"
structure as in C99 would be:

#v+
struct hai {
int id;
char sex;
union {
int age;
};
};
#v-

"case" insinde of a "record" in Pascal is very similar to "union" and
still your record hai will consume at least sizeof(integer) +
sizeof(boolean) + sizeof(integer) bytes no mether the value of sex.

--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl >--<jid:mina86*jab ber.org>--ooO--(_)--Ooo--
Oct 26 '06 #13
Andrew Poelstra <ap*******@fals e.sitewrote:
On Tue, 2006-10-24 at 07:04 -0700, Ancient_Hacker wrote:
Well, it's hardly worth the effort. If you're allocating with
malloc() there's typically a minium allocation of 8 to 16 bytes, so
saving the "age" field isn much of a savings. In fact often no savings
at all, if malloc does 16-byte alignment for speed.

Also, most people don't live more than 127 years, so you could store
the gender and age in one byte. Either with a union, or by some
convention, such as a signed char where -1 implies female, positive
implies male and gives their age.

Remember to quote context. Yours seems to be the cleverest solution to
the OP's problem, but few can remember what that problem was!
Clever, but also wrong. The signed char option works, but is rather
brittle and hard to maintain. The union option simply does not work. You
can't store two things in a byte with a union. You can store _either_
one _or_ the other, and writing to either destroys the other.

What might work, or might not, but is at least correct C, is to use
bitfields. 1 bit for the sex, 7 bits for the age. Both unsigned, of
course. Unfortunately there's no guarantee that you can use unsigned
chars for bitfields (only signed and unsigned int, and in C99 _Bool -
and implementation-defined types, so you _may_ be able to use unsigned
char, but it's not portable), so there's no guarantee that you save any
memory this way, over a simple non-bitfield unsigned char for both.

Richard
Oct 26 '06 #14

Michal Nazarewicz wrote:
"case" insinde of a "record" in Pascal is very similar to "union" and
still your record hai will consume at least sizeof(integer) +
sizeof(boolean) + sizeof(integer) bytes no mether the value of sex.

Ah, not exactly. If the record has a "discrimina ted" variant part,
meaning there's a variable in the record that indicates which variant
this is, as in this example, then when you make a new instance of the
record with new(), you can specify which variant record size you want,
for instance in the above example: new( Rec, true ) would allocate
only enough space for a record with the sex=true option.

Oct 26 '06 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2484
by: lixiaoyao | last post by:
hi all I use matrix & vector function to allocate the space myself in c, typedef struct matrix_array newdata; struct matrix_array{ float **sy,*sxx; }; newdata ndata;//new data struct ndata.sy=matrix(1,nvar,1,nstep); ndata.sxx=vector(1,nstep);
3
2254
by: Tony Johansson | last post by:
Hello! When you allocate object dynamically which mean on the heap I find that a problem when using exception. What is the prefer method to handle this kind of problem. //Tony
4
5004
by: marora | last post by:
I have created class definition which contains a charater pointer as one of it's data memeber. The objective is to read some data from a file, and assign it to a data member; Size of data is not known in the begining. We can assume that it will not exceed 256; class definition:
7
2807
by: Michael | last post by:
Hi, What's the benefit to dynamically allocate memory? using namespace std; int main() { char* ptr; ptr="abc";
2
3451
by: xhunga | last post by:
I have try a new version of my work. I have put the sizes of the matrix into the matrix. A = number of rows A = number of columns The first element of the matrix is A instead of A. You can not use the row 0, and the column 0.
5
1789
by: raghu | last post by:
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
20
2645
by: ramasubramanian.rahul | last post by:
hi folks i have a peculiar problem. i have to allocate more than size_t consequtive bytes on a system . after i do a malloc .. i am unable to do a realloc because it takes size_t as a new size and not as an incremental size.. can you tell me which library/system call to use.. Plz consider that all the physical hardware req for such an operation is available... i know this sounds crazy... but just help me out here .... Thanks in Advance
2
2991
by: lovecreatesbea... | last post by:
If the built-in operator keyword new doesn't allocate memory on heap and it calls global operator new (::operator new) or class member operator new to do that. What are the two kinds of operator new used to allocate heap memory? Before there aren't global and member operator new, the built-in operator keyword new does really allocate heap memory, right?
17
9149
by: dtschoepe | last post by:
Hi, I have a homework project I am working on, so be forwarned, I'm new to C programming. But anyway, having some trouble with a memory allocation issue related to a char * that is a variable inside of a structure. I keep getting segmentation fault errors and I am having trouble understanding why. Here's the parts of the code in question... This is part of the .h file where the struct us defined...
0
9491
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10357
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10163
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9959
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7510
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5532
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4063
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.