473,395 Members | 1,692 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

malloc a struct?

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
13 83848
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

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
[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


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


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
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
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
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
"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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

59
by: Steve Zimmerman | last post by:
This program compiles fine, but are there any hidden dangers in it, or is it ok? Experiment 1 ################################################## #include <stdio.h> #include <stdlib.h>...
34
by: Richard Hunt | last post by:
I'm sorry for asking such a silly question, but I can't quite get my head around malloc. Using gcc I have always programmed in a lax C/C++ hybrid (which I suppose is actually c++). But I have...
18
by: Panchal V | last post by:
I want to access a variable length record in C, the format is as follows : +---+---+-----------+ | A | L | D A T A | +---+---+-----------+ A - Some Data (1 BYTE) L - Length the Data that...
5
by: Grant Austin | last post by:
What would be the correct syntax for setting up a dynamic array of structs? Suppose you have a struct declared: struct relation { FILE * binFile; unsigned int numAttrs; struct attrList *...
20
by: fix | last post by:
Hi all, I feel unclear about what my code is doing, although it works but I am not sure if there is any possible bug, please help me to verify it. This is a trie node (just similar to tree nodes)...
7
by: Rano | last post by:
/* Hello, I've got some troubles with a stupid program... In fact, I just start with the C language and sometime I don't understand how I really have to use malloc. I've readden the FAQ...
40
by: Why Tea | last post by:
What happens to the pointer below? SomeStruct *p; p = malloc(100*sizeof(SomeStruct)); /* without a cast */ return((void *)(p+1)); /* will the returned pointer point to the 2nd...
23
by: raphfrk | last post by:
I am having an issue with malloc and gcc. Is there something wrong with my code or is this a compiler bug ? I am running this program: #include <stdio.h> #include <stdlib.h> typedef...
25
by: jbholman | last post by:
I am pretty new to C and doing my first project in C. I actually read almost the entire FAQ, but can't seem to figure out this problem. I have a structure. I have a list of these structures. ...
3
by: palidhjede | last post by:
Hi I'm having difficulties trying to malloc a struct this is what it looks like and how I'm approaching the problem. struct Records { char * fname; char * lname; }; Records** g_Recs;...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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,...
0
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...
0
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...
0
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...

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.