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?
There are no variables called
str1andstr2, so I’ll assume you meantptr1andptr2.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:
It’s a fairly bizarre piece of code, however. What are you actually trying to achieve? There may be a more elegant solution.