[Sussex] Re: C programming help - again!

Steve Dobson steve at dobson.org
Wed May 11 18:31:02 UTC 2005


On Wed, May 11, 2005 at 07:00:15PM +0100, Captain Redbeard wrote:
> Hi all,

Hi RB
 
> > Steve Dobson wrote:
> >
> > Your code has to handle this, for example:
> >
> >     TestStructPtr->CharLen = 13;
> >     TestStructPtr->CharString =
> >             (char *) malloc(TestStructPtr->CharLen + 1);
> > 	.
> > 	.
> > 	.
> >     const char *str = "Hello World!\n\n\n";
> >     bzero(TestStructPtr->CharString,
> >           TestStructPtr->CharLen + 1);
> >     strncpy (TestStructPtr->CharString, str,
> >              TestStructPtr->CharLen);
> 
> Thanks for pointing out the bzero() function, I didn't know 
> such a function existed and was planning to write my own! 
> You've saved me an hours work or so.

I suggest you speed some time and look at the various standard
C library calls.  
 
> In the second line of your code you've included a char cast 
> of the malloc() call, why is this cast necessary (I'm 
> assuming it's a cast although the in C '*' is a bit of a 
> swiss army knife)?

If you read the malloc spec it returns a pointer to a "void".
But you are assigning it to a pointer to a "char".  These are
_not_ the same types, the alignment of a void is very different
to the alignment of a char.  It is very good practice to let
everyone know (later developers and the compiler) that you are
aware of the change of type and this is what you want.  Remember
that the change of types is not just used with malloc() but all
over the place in a long C program.
 
Steve




More information about the Sussex mailing list