Search code examples
cstrdup

What is wrong with this c strdup code?


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?


Solution

  • 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.