473,770 Members | 2,096 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 #1
14 2641
raghu <ra*********@gm ail.comwrote:
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.
Then you can't use the structure like this - a structure _is_ the
set of its components and when you have the compiler create a new
instance of the structure it will give you memory for all its
members. The only way out is to have a pointer in the structure
that you assign memory to manually under certain conditions only,
like in (required error checking left out):

struct hai2 {
int id;
char sex;
int *age;
} person;

/* Assign some value to person.sex here */

if ( person.sex == 'M' ) {
person.age = malloc( sizeof *person.age );
*person.age = 17;
}

Of course, you also have to take care of deallocating the memory before
the structure goes out of scope.

Obvioulsy, this looks stupid in this example (the int pointer probably
requires at least as much memory as an integer), but there are several
situations where such an approach makes a lot of sense.

Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Oct 24 '06 #2

raghu wrote:
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
I suppose you could do something like this (error handling omitted for
brevity) :-

char sex;
int age;
struct hai *hp;
....
<processing to get the data to work with>
....
if (sex == 'M') {
hp = malloc(sizeof(s truct hai));
hp->id = <whatever>;
hp->sex = sex;
hp->age = age;
} else { /* I assume you've validate that sex is 'M' or 'F' */
hp = malloc(sizeof(s truct hai) - sizeof(int));
hp->id = <whatever>;
hp->sex = sex;
}

It's ugly and almost guaranteed to cause you grief in later times, but
it does (in some sense) meet your requirement.

However, your requirement is nonsense. Saving 1 machine word per
"struct hai" is not worth bothering with unless you are hugely
memory-constrained, IMNSHO...

Oct 24 '06 #3

mark_blue...@po box.com wrote:
..., your requirement is nonsense. Saving 1 machine word per
"struct hai" is not worth bothering with unless you are hugely
memory-constrained, IMNSHO...
As Jens points out, if there is more than just a single word, such as a
nested structure, the presence or absence of which is dependant on
other data in the structure, then a pointer-based solution may be
appropriate...

Oct 24 '06 #4
Okay but the problem is i have number of such type of members in a
structure. And instead of a byte I want to check the bit positions. If
i followed ur approach then i have to waste the memory of 4 bytes for
each member. But i don't want to happen like that.
-Raghu
Jens Thoms Toerring wrote:
raghu <ra*********@gm ail.comwrote:
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.

Then you can't use the structure like this - a structure _is_ the
set of its components and when you have the compiler create a new
instance of the structure it will give you memory for all its
members. The only way out is to have a pointer in the structure
that you assign memory to manually under certain conditions only,
like in (required error checking left out):

struct hai2 {
int id;
char sex;
int *age;
} person;

/* Assign some value to person.sex here */

if ( person.sex == 'M' ) {
person.age = malloc( sizeof *person.age );
*person.age = 17;
}

Of course, you also have to take care of deallocating the memory before
the structure goes out of scope.

Obvioulsy, this looks stupid in this example (the int pointer probably
requires at least as much memory as an integer), but there are several
situations where such an approach makes a lot of sense.

Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Oct 24 '06 #5
raghu <ra*********@gm ail.comwrote:
Okay but the problem is i have number of such type of members in a
structure. And instead of a byte I want to check the bit positions. If
i followed ur approach then i have to waste the memory of 4 bytes for
each member. But i don't want to happen like that.
One idea that buys you infinite flexibility at the cost of one void *,
one int, and 2^n-1 structure definitions (where n is the number of these
members that you don't want to automatically allocate memory for) -
making it a terribly silly idea, really - follows:

enum struct_types { FOO, BAR, FOO_AND_BAR };

struct my_struct {
int baz;
/* other fields */
int struct_type;
void *variable_struc t;
};

struct foo {
int foo;
};

struct bar {
int bar;
};

struct foo_and_bar {
int foo;
int bar;
};

struct my_struct *allocate_my_st ruct( int type ) {
/* Error checking of malloc() calls omitted */
struct my_struct *ret=malloc( sizeof *ret );
switch(type) {
case FOO:
ret->variable_struc t=malloc( sizeof(struct foo) );
break;
case BAR:
ret->variable_struc t=malloc( sizeof(struct bar) );
break;
case FOO_AND_BAR:
ret->variable_struc t=malloc( sizeof(struct foo_and_bar) );
break;
default:
ret->variable_struc t=NULL;
}
ret->struct_type=ty pe;
return ret;
}

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gma il.com | don't, I need to know. Flames welcome.
Oct 24 '06 #6

raghu wrote:
... the problem is i have number of such type of members in a
structure. And instead of a byte I want to check the bit positions. If
i followed ur approach then i have to waste the memory of 4 bytes for
each member. But i don't want to happen like that.
First point - don't top-post. It's greatly disliked in this group and
you'll lose such friends as you have.

Second point - if that is your problem, then you should have told us
about it first, rather than the trivial reduction of it. I think we
still need a clearer idea of what you are really trying to do before we
can give more than the most general guidance. Christopher's suggestion
seems fairly close though I'd also consider what could be achieved with
(for example) the use of unions...

Oct 24 '06 #7
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.

Oct 24 '06 #8
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. You can fake it somewhat by
defining TWO structs, one with and the other without the age field,and
malloc the right one each time.

Oct 24 '06 #9
raghu wrote:
>
Okay but the problem is i have number of such type of members in a
structure. And instead of a byte I want to check the bit positions.
If i followed ur approach then i have to waste the memory of 4
bytes for each member. But i don't want to happen like that.
Don't top-post, or you will likely be ignored in this group. Your
answer belongs after, or possibly intermixed with, the _snipped_
material you quote. Also you should improve your spelling. The
first person pronoun is I, capitalized. 'your' is spelt as shown.
Using such abortions as i and ur only makes your post hard to read
and is offensive.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

Oct 24 '06 #10

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
5002
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
2805
by: Michael | last post by:
Hi, What's the benefit to dynamically allocate memory? using namespace std; int main() { char* ptr; ptr="abc";
2
3450
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
9148
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
9454
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
10260
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
10101
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...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8933
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7456
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
6712
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.