Thread: Struct storage with char* type ?

  1. #1
    GrandmaMike
    Guest

    Struct storage with char* type ?

    Here's the problem, ...

    /*===================*/
    Struct identifier
    {
    char* name;
    int value;
    }

    struct identifier id[100];

    /*===================*/

    So, basically I have an array of structures.....

    Lets say I have....

    /*====================*/
    char **tokenbuffer;

    id[0].name = tokenbuffer[0];
    id[1].name = tokenbuffer[1];

    etc....

    Then,... I eventually NULL out all the cells of tokenbuffer in a for loop.

    The problem is that once I do this, I wipe out the id[].name
    values in my struct as well. I suppose this is because I'm really
    storing a pointer in id[].name because it is of type char*. How
    can I resolve this problem, i.e. keep the struct from changing
    when I alter tokenbuffer ?

    -jay

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    34,696
    Use malloc

    id[0].name = malloc( strlen(tokenbuffer[0]) + 1 );
    strcpy( id[0].name, tokenbuffer[0] );

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    > How can I resolve this problem, i.e. keep the struct from
    > changing when I alter tokenbuffer ?

    The problem is, you're making the structure point to the 'tokenbuffer'. Naturally, when you make changes to the 'tokenbuffer', you affect whatever is pointing at it.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 06:55 PM
  2. Replies: 1
    Last Post: 12-03-2008, 03:10 AM
  3. Replies: 10
    Last Post: 05-19-2006, 12:23 AM
  4. Learning OpenGL
    By HQSneaker in forum C++ Programming
    Replies: 7
    Last Post: 08-06-2004, 09:57 AM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
Website Security Test