malloc a struct?

M

mike79

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
 
B

Ben Pfaff

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.
 
J

Jason

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.
 
A

Artie Gold

[top-posting corrected]
> 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
 
E

Ed Morton

mike79 said:
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.
 
F

Fao, Sean

mike79 said:
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
 
F

Fao, Sean

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.
 
E

Ed Morton

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
 
D

Dan Pop

In said:
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
 
F

Fao, Sean

Dan said:
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.
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.
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
 
D

Dan Pop

In said:
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
 
B

Ben Pfaff

Fao said:
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.
 
S

Sidney Cadot

Mark said:
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=...malloc&ie=ISO-8859-1&hl=en&btnG=Google+Search

Best regards,

Sidney
 

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,104
Messages
2,570,643
Members
47,247
Latest member
youngcoin

Latest Threads

Top