By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,977 Members | 1,638 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,977 IT Pros & Developers. It's quick & easy.

malloc a struct?

P: n/a
hi all..

if I wanted to malloc a struct, say the following:

struct myStruct1
{
int number;
char *string;
}

how would I do this?

Would I need to first malloc myStruct, then malloc string?

Ive seen some malloc commands around, so are:

myStruct1 = malloc(sizeof (myStruct1));
myStruct1 = malloc(sizeof (* myStruct1));
myStruct1 = malloc(sizeof (myStruct1 *));

Can anyone tell me the difference please??

Thank you all for your help! much appreciated!
mike79
Nov 13 '05 #1
Share this Question
Share on Google+
13 Replies


P: n/a
mi****@iprimus.com.au (mike79) writes:
if I wanted to malloc a struct, say the following:

struct myStruct1
{
int number;
char *string;
}

how would I do this?
struct myStruct1 *s = malloc (sizeof *s);

After that, you can assign to s->string memory allocated for the
string, say with something like
s->string = malloc (strlen (myString) + 1);
Would I need to first malloc myStruct, then malloc string?
That's the most straightforward approach. You definitely can't
assign to the string member of a structure object that hasn't yet
been allocated, although you could allocate the memory for the
string.
Ive seen some malloc commands around, so are:
C doesn't have commands. malloc() is a function in the standard
C library.
myStruct1 = malloc(sizeof (myStruct1));
That'd have to be sizeof (struct myStruct1) based on your
definition above.

Also, it is confusing to name both the structure and a pointer to
an object of the structure's type `myStruct1'.

When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type. For instance,
*don't* write this:

int *x = malloc (sizeof (int) * 128); /* Don't do this! */

Instead, write it this way:

int *x = malloc (sizeof *x * 128);

There's a few reasons to do it this way:

* If you ever change the type that `x' points to, it's not
necessary to change the malloc() call as well.

This is more of a problem in a large program, but it's still
convenient in a small one.

* Taking the size of an object makes writing the statement
less error-prone. You can verify that the sizeof syntax is
correct without having to look at the declaration.
myStruct1 = malloc(sizeof (* myStruct1));
That's better, although again I'd give the structure and the
object different names.
myStruct1 = malloc(sizeof (myStruct1 *));


Wrong.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 13 '05 #2

P: n/a

better to define struct like this:

typedef struct {
int number;
char *string;
}myStruct1;

to malloc you can do this, creating your pointer.

myStruct1 *name = (myStruct *) malloc(sizeof(myStruct1));

you are supposed to check to see if malloc returns null also for error
handling

to reference elements within your struct pointer just use this syntax.
name->number = x;
and to malloc the pointer within the struct:

name->string = malloc(number);

number being characters u want

-> is used when u are dealing with a pointer to a structure otherwise its
the usual 'structname.structmember' syntax.

"mike79" <mi****@iprimus.com.au> wrote in message
news:49*************************@posting.google.co m...
hi all..

if I wanted to malloc a struct, say the following:

struct myStruct1
{
int number;
char *string;
}

how would I do this?

Would I need to first malloc myStruct, then malloc string?

Ive seen some malloc commands around, so are:

myStruct1 = malloc(sizeof (myStruct1));
myStruct1 = malloc(sizeof (* myStruct1));
myStruct1 = malloc(sizeof (myStruct1 *));

Can anyone tell me the difference please??

Thank you all for your help! much appreciated!
mike79

Nov 13 '05 #3

P: n/a
[top-posting corrected]

Jason wrote:

"mike79" <mi****@iprimus.com.au> wrote in message
news:49*************************@posting.google.co m...
hi all..

if I wanted to malloc a struct, say the following:

struct myStruct1
{
int number;
char *string;
}

how would I do this?

Would I need to first malloc myStruct, then malloc string?

Ive seen some malloc commands around, so are:

myStruct1 = malloc(sizeof (myStruct1));
myStruct1 = malloc(sizeof (* myStruct1));
myStruct1 = malloc(sizeof (myStruct1 *));

Can anyone tell me the difference please??

Thank you all for your help! much appreciated!
better to define struct like this:

typedef struct {
int number;
char *string;
}myStruct1;

to malloc you can do this, creating your pointer.

myStruct1 *name = (myStruct *) malloc(sizeof(myStruct1));
The cast is unnecessary and can hide the error of failing to
#include <stdlib.h>

Stylistically, this would be better:

myStruct1 *name = malloc(sizeof *name);

as, if the type should happen to change, you only need to change it
in *one* place.

you are supposed to check to see if malloc returns null also for error handling

to reference elements within your struct pointer just use this syntax. name->number = x;
and to malloc the pointer within the struct:

name->string = malloc(number);

number being characters u want
Of course, you should really make that:

name->string = malloc(number + 1);

to account for the trailing null character in C-style strings.

-> is used when u are dealing with a pointer to a structure otherwise its the usual 'structname.structmember' syntax.


HTH,
--ag
--
Artie Gold -- Austin, Texas
Oh, for the good old days of regular old SPAM.

Nov 13 '05 #4

P: n/a


mike79 wrote:
hi all..

if I wanted to malloc a struct, say the following:

struct myStruct1
{
int number;
char *string;
}

how would I do this?

Would I need to first malloc myStruct, then malloc string?

Ive seen some malloc commands around, so are:

myStruct1 = malloc(sizeof (myStruct1));
myStruct1 = malloc(sizeof (* myStruct1));
myStruct1 = malloc(sizeof (myStruct1 *));

Can anyone tell me the difference please??

Thank you all for your help! much appreciated!
mike79


You already got some explanations but if you're still not sure, try
running this program:

#include "stdio.h"

struct TAG10 {
char x[10];
};

typedef struct {
char x[20];
} TYPE20;

int main (void)
{
struct TAG10 *pTag;
TYPE20 *pType;

printf("Size of the structure tagged TAG10 = %d\n",sizeof (struct
TAG10));
printf("Size of whatever is pointed to by pTag = %d\n",sizeof *pTag);
printf("Size of the pointer pTag = %d\n",sizeof pTag);
printf("Size of a pointer of type \"struct TAG10*\" = %d\n",sizeof
(struct TAG10*));
printf("Size of the type TYPE20 = %d\n",sizeof (TYPE20));
printf("Size of whatever is pointed to by pType = %d\n",sizeof *pType);
printf("Size of the pointer pType = %d\n",sizeof pType);
printf("Size of a pointer of type \"TYPE20*\" = %d\n",sizeof
(TYPE20*));
return 0;
}

and the output should make it clear what the various uses of sizeof are
doing, which should explain how it's used in the various malloc() calls:

Size of the structure tagged TAG10 = 10
Size of whatever is pointed to by pTag = 10
Size of the pointer pTag = 4
Size of a pointer of type "struct TAG10*" = 4
Size of the type TYPE20 = 20
Size of whatever is pointed to by pType = 20
Size of the pointer pType = 4
Size of a pointer of type "TYPE20*" = 4

I threw in the type vs tag stuff since someone else mentioned it so you
could see the difference in how the 2 are used.

Ed.

Nov 13 '05 #5

P: n/a
mike79 wrote:
char *string;


I don't want to give the false impression that I have read the C99
standard in its entirety and I don't have a copy of it in front of me to
refer to but assumming that no string data type exists in the C99
standard, is it just me or should we avoid naming anything "string" for
preperation in the event that a string data type is eventually added to
the C standard? Granted, if it's not already a data type in the
standard, it probably never will be; but, who's to say that our code
won't one day be converted to C++?

Sean

Nov 13 '05 #6

P: n/a
Fao, Sean wrote:
mike79 wrote:
char *string;

I don't want to give the false impression that I have read the C99
standard in its entirety and I don't have a copy of it in front of me to
refer to but assumming that no string data type exists in the C99
standard, is it just me or should we avoid naming anything "string" for
preperation in the event that a string data type is eventually added to
the C standard? Granted, if it's not already a data type in the
standard, it probably never will be; but, who's to say that our code
won't one day be converted to C++?


Oh crap, forgot to run spell check before I sent this.

Nov 13 '05 #7

P: n/a


Fao, Sean wrote:
mike79 wrote:
char *string;

I don't want to give the false impression that I have read the C99
standard in its entirety and I don't have a copy of it in front of me to
refer to but assumming that no string data type exists in the C99
standard, is it just me or should we avoid naming anything "string" for
preperation in the event that a string data type is eventually added to
the C standard?


Whether or not it eventually is added to the C standard doesn't really
matter. We should avoid naming any variable "string" because that's just
a really poor name for a variable as it describes what the variable is
(i.e. a string) not what it's purpose is (e.g. a name, address, ...). In
the same light, you'd never really name a structure tag "myStruct1".

Ed.

Granted, if it's not already a data type in the standard, it probably never will be; but, who's to say that our code
won't one day be converted to C++?

Sean


Nov 13 '05 #8

P: n/a
In <3F**************@yahoo.comI-WANT-NO-SPAM> "Fao, Sean" <en**********@yahoo.comI-WANT-NO-SPAM> writes:
mike79 wrote:
char *string;
I don't want to give the false impression that I have read the C99
standard in its entirety and I don't have a copy of it in front of me to
refer to


Then, it is a good idea to let those who have read the standard (or, at
least, can consult it) speak on the issue.
but assumming that no string data type exists in the C99
standard, is it just me or should we avoid naming anything "string" for
preperation in the event that a string data type is eventually added to
the C standard?
First, you have removed the context, which is always a BAD thing. That
declaration is part of a struct definition. According to the standard,
there is no conflict and the identifier name is perfectly OK.

There is little point in guessing what a future standard may add. It
may be a keyword named "string", but it may be a keyword named "foo".
The ONLY thing that matters is that the current standard allows the
usage of the identifier "string" in this context. It does prohibit
its usage as an external identifier, however.
Granted, if it's not already a data type in the
standard, it probably never will be; but, who's to say that our code
won't one day be converted to C++?


How about FORTRAN, Pascal, Ada, LISP, PROLOG, Forth, Java and so on?
When writing C code, it is best to care about the code correctness from
C's point of view.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #9

P: n/a
Dan Pop wrote:
In <3F**************@yahoo.comI-WANT-NO-SPAM> "Fao, Sean" <en**********@yahoo.comI-WANT-NO-SPAM> writes:

mike79 wrote:

char *string;
I don't want to give the false impression that I have read the C99
standard in its entirety and I don't have a copy of it in front of me to
refer to

Then, it is a good idea to let those who have read the standard (or, at
least, can consult it) speak on the issue.


Agreed, this is why I made it clear that I did *NOT* have a way of
verifying.
but assumming that no string data type exists in the C99
standard, is it just me or should we avoid naming anything "string" for
preperation in the event that a string data type is eventually added to
the C standard?

First, you have removed the context, which is always a BAD thing. That
declaration is part of a struct definition. According to the standard,
there is no conflict and the identifier name is perfectly OK.


The standard as of now.
There is little point in guessing what a future standard may add. It
may be a keyword named "string", but it may be a keyword named "foo".
The ONLY thing that matters is that the current standard allows the
usage of the identifier "string" in this context. It does prohibit
its usage as an external identifier, however.


A valid argument but, for once, I tend to disagree with what you
suggest. To me, this is no different then somebody planning ahead for
future porting on another platform.
Granted, if it's not already a data type in the
standard, it probably never will be; but, who's to say that our code
won't one day be converted to C++?


How about FORTRAN, Pascal, Ada, LISP, PROLOG, Forth, Java and so on?
When writing C code, it is best to care about the code correctness from
C's point of view.


Again, to me, it's no different then planning ahead for it to be ported
to another platform. I'm not suggesting the we plan ahead for every
language, that would be ludicrous and extremely time consuming. I am
however suggesting that where syntax is very similar (IE C++), we
consider the possibility that our code may be used in another project,
possibly written in C++.

Now before you take this the wrong way, I'm merely talking about some
minor things such as reserved words, etc. As you well know, OO style is
drastically different and I am not suggesting that we plan ahead for and
write our C code more OO-like unless it's the best way to get the job done.

I'm already convinced that you will not agree with what I have just
posted but it is my opinion and I am entitled to that.

Sean

Nov 13 '05 #10

P: n/a
In <bp********@netnews.proxy.lucent.com> Ed Morton <mo****************@lucent.com> writes:
Fao, Sean wrote:
mike79 wrote:
char *string;


I don't want to give the false impression that I have read the C99
standard in its entirety and I don't have a copy of it in front of me to
refer to but assumming that no string data type exists in the C99
standard, is it just me or should we avoid naming anything "string" for
preperation in the event that a string data type is eventually added to
the C standard?


Whether or not it eventually is added to the C standard doesn't really
matter. We should avoid naming any variable "string" because that's just
a really poor name for a variable as it describes what the variable is
(i.e. a string) not what it's purpose is (e.g. a name, address, ...). In
the same light, you'd never really name a structure tag "myStruct1".


You're a victim of Fao's abusive snipping the included text. It's not
a variable declaration, it's a struct member declaration. Depending on
the struct's actual purpose, "string" may or may not be an adequate name.
If the struct is generic enough, it is an excellent way of pointing out
that this member is supposed to point to a string whose contents has no
particular meaning (e.g. a name, address, ...). Imagine that you're
implementing a generic binary tree, associating a numeric value to any
arbitrary string for example. It can be used as a symbol table, but it
can also be used as a way of retrieving a person's SSN.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #11

P: n/a
"Fao, Sean" <en**********@yahoo.comI-WANT-NO-SPAM> writes:
I don't want to give the false impression that I have read the C99
standard in its entirety and I don't have a copy of it in front of me
to refer to but assumming that no string data type exists in the C99
standard, is it just me or should we avoid naming anything "string"
for preperation in the event that a string data type is eventually
added to the C standard?


No. No future C standard will add `string' as a keyword because
it would break too many existing programs.
--
"The lusers I know are so clueless, that if they were dipped in clue
musk and dropped in the middle of pack of horny clues, on clue prom
night during clue happy hour, they still couldn't get a clue."
--Michael Girdwood, in the monastery
Nov 13 '05 #12

P: n/a
On Thu, 13 Nov 2003 02:00:15 +0000 (UTC), in comp.lang.c , "Jason"
<ja***********@btinternet.com> wrote:
myStruct1 *name = (myStruct *) malloc(sizeof(myStruct1));


don't cast malloc() when writing C code. It serves no useful purpose
and can hide errors.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
Nov 13 '05 #13

P: n/a
Mark McIntyre wrote:
On Thu, 13 Nov 2003 02:00:15 +0000 (UTC), in comp.lang.c , "Jason"
<ja***********@btinternet.com> wrote:

myStruct1 *name = (myStruct *) malloc(sizeof(myStruct1));

don't cast malloc() when writing C code. It serves no useful purpose
and can hide errors.


For the record, without trying to instigate new discussion, and in full
realization that I represent a small minority, I would like to mention
that I beg to differ on this issue.

The OP might wish to consult the thread below to assess the pros and
cons of casting malloc results:

http://groups.google.com/groups?hl=e...oogle%2BSearch

Best regards,

Sidney

Nov 13 '05 #14

This discussion thread is closed

Replies have been disabled for this discussion.