September 22nd, 2003, 03:56 PM
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..
I then create an array of these structs and use a method to enter the values for the struct.
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. 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.
//taskT buildTask(char *, int, int);
taskList[n]= buildTask(statusfile, PIDs, nt);
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
Last edited by unityxx311; September 22nd, 2003 at 03:59 PM.
September 22nd, 2003, 04:47 PM
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:
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.
// if C, then cmdName = (char*)malloc(strlen(statusfile)+1);
// else if C++, cmdName = new char[strlen(statusfile)+1];