-
Thank You
First, I just wanted to thank everyone who replies to all these threads for the sole purpose of helping someone to learn. I think its great that people like you are around helping others. I'm a begining C programmer and have never participated in a thread, but have been reading other people's threads for a while in order to learn, and am always impressed by the good advice and care that is posted on this site. Thank you all.
Now for a quick question ;-)
I am trying to use the memset command to fill up a structure with #'s, but it doesn't seem to be working. Each part of the structure is only 16 bytes, but the memset seems to only fill up four characters.
Anyway, here is the structure defined and the way I've been using memset:
typedef struct phoneTemplate
{
char lastName[16];
char firstName[16];
char phoneNumber[16];
}phoneRec;
...program here...
then the initialization and use of the memset line.
jones = (phoneRec *)malloc(sizeof(phoneRec));
if (jones==NULL)
{ perror("struct1"); exit(1); }
memset(jones,'#',sizeof(jones));
Thanks in advance for any help.
Joe
-
That is because jones is a pointer to a struct and not a struct itself. In the 32-bit world, all pointers are 4-bytes and that is why only the first four bytes are being set. You need to use memset(jones,'#',sizeof(*jones));. The sizeof(*jones) means get the size of what the jones pointer points to (the size of the struct).
-
jones is a pointer, which is a 4-byte value indicating the address of the structure which you wish to fill. Either of these should work...
Code:
memset(jones,'#',sizeof(*jones));
// or...
memset (jones, '#', sizeof (phoneRec));
-
>memset(jones,'#',sizeof(jones));
The problem is here, jones is a pointer consisting of four bytes. So memset only fills four bytes of the structure instance. A better way would be to dereference the pointer and get the actual size of the memory allocated, or use sizeof on the structure instead of the instance. I prefer the former because it doesn't bind memset too closely to the structure, you can change jones to another structure and this would work:
memset ( jones, '#', sizeof *jones );
But this would not:
memset ( jones, '#', sizeof ( phoneRec ) );
However, in this case it doesn't matter, you can use either one and they will both fill the contents of the structure with # symbols.
[edit]I was so slow on this one ;)[/edit]
-Prelude
-
Thanks so much for all your help. I didn't even know you could change a variable from one structure to another ;-)
I think data structures is next semester!
Joe