这个 c strdup 代码有什么问题?
考虑这段代码:
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);
我希望输出“string1\nstring2\n”,但 str1 和 str2 保持为空。我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
没有名为
str1
和str2
的变量,因此我假设您指的是ptr1
和ptr2
。您从未向这些变量分配任何内容,因此它们没有理由更改其原始值。我认为这就是您的意图:
然而,这是一段相当奇怪的代码。你到底想达到什么目的?可能有更优雅的解决方案。
There are no variables called
str1
andstr2
, so I'll assume you meantptr1
andptr2
.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.
您没有为
ptr1
和ptr2
赋值。你可以做类似的事情:或者更简单:
You're not assigning values to
ptr1
andptr2
. You can do something like:or even simpler:
事实上,ptr1 和 ptr2 都没有更新。
从表面上看,您试图在 tmp 更新时更新 ptr1 和 ptr2 。为此, tmp 需要是一个双指针,并且您的代码需要看起来像......
希望这会有所帮助。
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 ...
Hope this helps.
您永远不会为
ptr1
和ptr2
赋值。使用tmp = ptr1
,您只需将ptr1
的当前值(NULL)复制到tmp
。但是,之后更改tmp
不会影响ptr1
的值。这就是指针的工作原理。试试这个:
或者重新声明并使用 tmp 作为指向指针的指针,正如 @Marcelo Cantos 在他的答案中演示的那样。
You never assign a value to
ptr1
andptr2
. Withtmp = ptr1
, you just copy the current value ofptr1
(which is NULL) over totmp
. However, changingtmp
afterwards does not affect the value ofptr1
. This is how it works with pointers.Try this instead:
Or redeclare and use
tmp
as a pointer to pointer, as @Marcelo Cantos demonstrates in his answer.您声明 ptr1 和 ptr2 并将它们初始化为 null,但随后不设置它们的值。
You declare ptr1 and ptr2 and initialise them to null, but you don't subsequently set their values.
将 ptr1 和 ptr2 初始化为 NULL,并且从不更改它们。所以他们没有指出任何事情。
You initialize ptr1 and ptr2 to NULL, and never change them. So they point to nothing.