-
pointers and arrays
quick problem if anyone can help i have the following code as part of my program:
int pointercounter = 0;
char tempname[30] = "";
int tempcounter = 0;
char *testing[30];
while (in_stream >> value &&value != '('){
tempname [tempcounter] = value;
tempcounter++;
}//to get the next name on the line
testing[pointercounter] = tempname;
pointercounter++;
the above while loop is nested within another while loop so *testing is being filled up but will never exceed its limit
the problem is later in teh program i try something like
cout<<tetsing[0];
it results in nothing being outputed,
however if inside the while loop i insert a command
cout<<testing[pointercounter];
just after the assignment testing[pointercounter]= tempname
then it outputs the correct string ?????
im not sure what i am doing wrong or if someone can explain to me what is happening that would be great
thanks in advance for ur help
yours pants
-
Be very carefull with pointers.
testing[pointercounter] = tempname;
When you copy the tempname to testing you only copy the pointer. The next time you change tempname you also change testing because they both point to the same space. Try using strcpy to copy the complete string.
The simplest way to solve this problem is to do the following:
Code:
int pointercounter = 0;
char tempname[30] = "";
int tempcounter = 0;
// char *testing[30];
char testing[100][30];
while (in_stream >> value &&value != '(')
{
tempname [tempcounter] = value;
tempcounter++;
} //to get the next name on the line
// testing[pointercounter] = tempname;
strcpy(testing[pointercounter], tempname);
pointercounter++;
You can read max 100 names using this array.
A better (and more difficult way) to solve this is by using dynamic arrays.
Code:
int pointercounter = 0;
char tempname[30] = "";
int tempcounter = 0;
// char *testing[30];
char **testing = NULL;
while (in_stream >> value &&value != '(')
{
tempname [tempcounter] = value;
tempcounter++;
} //to get the next name on the line
// testing[pointercounter] = tempname;
testing = realloc(testing, sizeof(char *) * (pointercounter + 1)); // allocate space for new index
testing[pointercounter] = strdup(tempname); // allocate space and copy string
pointercounter++;
Don't forget to remove allocated memory afterwards when using dynamic arrays.