gpt4 book ai didi

c - 为函数 C 中复制的指针赋值

转载 作者:行者123 更新时间:2023-11-30 15:18:12 24 4
gpt4 key购买 nike

我有这个:

typedef struct{
int x;
int y;
}T;
void f(T** t)
{
T t1;
*t=malloc(sizeof(T)*T_MAX_SIZE);
t1.x=11;
t1.y=12;
(*t)[0] = t1;
}

我希望它能够移动指针,而不是使用位置,我不太确定问题出在哪里或是什么,代码:

void f(T** t)
{
T t1;
T t2;
T** copy=t;
*t=malloc(sizeof(T)*T_MAX_SIZE);
t1.x=11;
t1.y=12;
t2.x=21;
t2.y=22;
**copy=t1;
copy++;
**copy=t2;

}
int main()
{
T* t;
f(&t);
printf("%i %i\n",t[0].x,t[1].x);
free(t);
}

这是以下线程的继续 -> Copying Struct to a Pointer array in a function C

这不起作用:/

最佳答案

您的间接级别是错误的。应该是:

void f(T** t)
{
T t1;
T t2;
T* copy = *t = malloc(sizeof(T)*T_MAX_SIZE);
t1.x=11;
t1.y=12;
t2.x=21;
t2.y=22;
*copy=t1;
copy++;
*copy=t2;
}

您发布的代码将前进到仅包含单个元素的序列中的“下一个”T*,即由 &t 回到 main( )。不存在这样的“下一个”元素,因此您的代码会调用未定义的行为。你很幸运它没有彻底崩溃。

关于c - 为函数 C 中复制的指针赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31619854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com