[plug] [OT] Arg!! C Pointers on Char Arrays

Timothy White weirdo at tigris.org
Sat Feb 19 10:12:11 WST 2005


I am having some problems with pointers in C. Now I don't want someone
to say go to C++ or something like that. I am using someone else's code
and adding parts to get it to do what I want.

Basically I have a struct of form:
struct critter
  {
    const char *name;
    const char *species;
  };

and I define a global array of this struct.:
struct critter muppets[100];

Later on I have a loop in main that reads in 'critters' into the array.
  while(1) {
        fscanf(BAD, "%s\n", &word);
        if(!strcmp("#",word))break;
        printf("%d:Adding word '%s'\n", count, word);
        muppets[count].name = word;
        muppets[count].species = word;
        count++;
  }

The problem is putting the data into the array. I understand that I have
an array of pointers and word is also a pointer. SO by doing it like I
have I am copying the pointer so I end up with all the muppets pointing
to the same bit of memory which is the # as that is the last character.
This I obviously don't want. I want to copy the data not the pointer.
Every combination of * & and -> that I have tried fails. I also tried
strcpy but got nowhere: (All below failed)
        strcpy(muppets[count].name,word);
        &muppets[count].name = word;
        &muppets[count].species = word;

Anyone please point out my simple mistake. It's been /way/ too long
since I programmed in C and have gotten used to perl and PHP style again.

Tim

--
Tim White - Use the Fox, Luke!
PGP/GPG id: 602E944D, Pub Key Serv: subkeys.pgp.net
Fingerprint: 04C2 9682 B7B2 3006 009D  A9F3 067E EDCD 602E 944D
Hi! I'm a .signature virus! Copy me into your ~/.signature to help me spread!
--

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: OpenPGP digital signature
URL: <http://lists.plug.org.au/pipermail/plug/attachments/20050219/f05a470a/attachment.pgp>


More information about the plug mailing list