#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    6
    Rep Power
    0

    Arrow problem with a group of pointers all pointing to same mem.location


    Hi- I have a struct that has a pointer to a char array..

    Code:
    struct task
    {
    char *cmdName;
    int pid;
    int nice;
    int size;
    int res;
    };

    I then create an array of these structs and use a method to enter the values for the struct.
    Code:
    taskT taskList[30];
    
    //taskT buildTask(char *, int, int);
    taskList[n]= buildTask(statusfile, PIDs, nt);
    
    
    //example print/*
    task: (rwhod)  pid: 1   status:  S
    task: (rwhod)  pid: 2   status:  S
    task: (rwhod)  pid: 3   status:  S
    task: (rwhod)  pid: 4   status:  S
    task: (rwhod)  pid: 5   status:  S
    task: (rwhod)  pid: 6   status:  S
    task: (rwhod)  pid: 7   status:  S
    task: (rwhod)  pid: 11   status:  S
    ... */
    The problem is apparent when I print out taskList and see that all of the taskT's have the same cmdName, which is the last one assigned taskList[29]. How might I be able to pick a new pointer location every time I enter buildTask() for cmdName, so they do not all have the same value.

    thx.matt
    Last edited by unityxx311; September 22nd, 2003 at 03:59 PM.
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,143
    Rep Power
    2222
    I assume that in buildTask you accept a char* as a parameter and simply assign that pointer value to cmdName. Furthermore, I assume that the char pointer you pass to buildTask was only allocated once and then each time you prepare the call to buildTask you just load it with the new string -- yet the pointer still points to the same location all the time.

    You could either create a new string allocation before calling buildTask ... .

    Or better, within buildTask dynamically allocate memory for cmdName and copy the string parameter into it:
    Code:
    // if C, then cmdName = (char*)malloc(strlen(statusfile)+1);
    // else if C++, cmdName = new char[strlen(statusfile)+1];
    strcpy(cmdName,statusfile);
    I also had to unlearn habits from other languages' handling of strings. Assigning char array names only assigns a pointer to the same location. To make a separate copy you need to allocate the space and explicitly copy the contents.

IMN logo majestic logo threadwatch logo seochat tools logo