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

assigning values to a copied pointer in a function C

我有这个:

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

这是后续话题的延续 ->

这行不通:/

你的间接层次是错误的。应该是:

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;    
}

您发布的代码在仅包含一个元素的序列中前进到 "next" T*,即 &tmain() 中提到的那个。没有这样的 "next" 元素,因此您的代码会调用未定义的行为。你真(不)走运它没有彻底崩溃。