tags:

views:

129

answers:

6

Consider this code:

char *strs[] = { "string1", "string2", NULL };
char *ptr1 = NULL, *ptr2 = NULL, *tmp;
short iter = 0;

tmp = ptr1;
while (iter < 2)
{
   tmp = strdup(strs[iter]);
   tmp = ptr2;
   iter++;
}

printf("1: %s\n2: %s\n", ptr1, ptr2);

I want this to output "string1\nstring2\n" however str1 and str2 remain null. What am I doing wrong?

+2  A: 

You never assign a value to ptr1 and ptr2. With tmp = ptr1, you just copy the current value of ptr1 (which is NULL) over to tmp. However, changing tmp afterwards does not affect the value of ptr1. This is how it works with pointers.

Try this instead:

ptr1 = strdup(strs[0]);
ptr2 = strdup(strs[1]);

Or redeclare and use tmp as a pointer to pointer, as @Marcelo Cantos demonstrates in his answer.

Péter Török
+5  A: 

There are no variables called str1 and str2, so I'll assume you meant ptr1 and ptr2.

You never assign anything to these variables, so there's no reason for them to change from their original values. I think this is what you intended:

char *strs[] = { "string1", "string2", NULL };
char *ptr1 = NULL, *ptr2 = NULL, **tmp;
short iter = 0;

tmp = &ptr1;
while (iter < 2)
{
   *tmp = strdup(strs[iter]);
   tmp = &ptr2;
   iter++;
}

printf("1: %s\n2: %s\n", ptr1, ptr2);

It's a fairly bizarre piece of code, however. What are you actually trying to achieve? There may be a more elegant solution.

Marcelo Cantos
The real code is looping through a binary file until it finds 'patternA' then stores some data that comes after 'patternA' in a struct, on the 2nd loop it switches to a new pattern 'patternB' and stores some data that comes after it in another value in that struct.
@bstullkid: In such a case, it may be simpler to just write two loops.
Marcelo Cantos
+1  A: 

You declare ptr1 and ptr2 and initialise them to null, but you don't subsequently set their values.

Andy Johnson
+1  A: 

You initialize ptr1 and ptr2 to NULL, and never change them. So they point to nothing.

Dave Costa
+2  A: 

You're not assigning values to ptr1 and ptr2. You can do something like:

while (iter < 2) {
    tmp = strdup(strs[iter]);
    if(iter == 0)
        ptr1 = tmp;
    else if(iter == 1)
        ptr2 = tmp;
    iter++;
}

or even simpler:

ptr1 = strdup(strs[0]);
ptr2 = strdup(strs[1]);
codaddict
+2  A: 

As it is, neither ptr1 nor ptr2 are updated.

From the looks of it, you are trying to have ptr1 and ptr2 updated when tmp is updated. To do this, tmp would need to be a double pointer and your code would need to look like ...

char *strs[] = { "string1", "string2", NULL };
char *ptr1 = NULL, *ptr2 = NULL, **tmp;
short iter = 0;

tmp = &ptr1;
while (iter < 2)
{
   *tmp = strdup(strs[iter]);
   tmp = &ptr2;
   iter++;
}

printf("1: %s\n2: %s\n", ptr1, ptr2);

Hope this helps.

Sparky