开发者

What is wrong with this c strdup code?

开发者 https://www.devze.com 2022-12-29 06:31 出处:网络
Consider this co开发者_运维问答de: char *strs[] = { \"string1\", \"string2\", NULL }; char *ptr1 = NULL, *ptr2 = NULL, *tmp;

Consider this co开发者_运维问答de:

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


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]);


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.


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号