簡體   English   中英

在C中通過引用傳遞指向struct的指針

[英]Pass pointer to struct by reference in C

請記住以下代碼:

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int a;
    int b;
    int c;
}A;

A *test;

void init(A* a)
{
    a->a = 3;
    a->b = 2;
    a->c = 1;
}
int main()
{
    test = malloc(sizeof(A));
    init(test);
    printf("%d\n", test->a);
    return 0;
}

它運行正常! 現在假設我想在main之外使用malloc函數而不返回指向struct的指針。 我會將malloc放在init並通過test地址。 但這似乎不起作用。

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int a;
    int b;
    int c;
}A;

A *test;

void init(A** a)
{
    *a = malloc(sizeof(A));
    *a->a = 3;
    *a->b = 2;
    *a->c = 1;
}
int main()
{
    init(&test);
    printf("%d\n", test->a);
    return 0;
}

它使告訴我,詮釋a (或b / c )不是的成員struct A當我使用指針。

您必須添加括號:

void init(A **a)
{
    *a = malloc(sizeof(A)); // bad you don't verify the return of malloc
    (*a)->a = 3;
    (*a)->b = 2;
    (*a)->c = 1;
}

但這樣做是很好的做法:

void init(A **a)
{
    A *ret = malloc(sizeof *ret); // we want the size that is referenced by ret
    if (ret != NULL) { // you should check the return of malloc
        ret->a = 3;
        ret->b = 2;
        ret->c = 1;
    }
    *a = ret;
}

你需要寫(*a)->a = 3; 出於優先原因。

您的問題是運營商優先級。 ->運算符的優先級高於* (取消引用)運算符,因此*a->a的讀取就像它是*(a->a) *a->a更改為(*a)->a

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int a;
    int b;
    int c;
}A;

A *test;

void init(A** a)
{
    *a = malloc(sizeof(A));
    (*a)->a = 3;
    (*a)->b = 2;
    (*a)->c = 1;
}
int main()
{
    init(&test);
    printf("%d\n", test->a);
    return 0;
}

即使它不是你問題的直接答案,因為我們正處於初始化的附近,我想指出C11為你提供了一個更好的語法來初始化結構:

void init(A **a)
{
    A *ret = malloc(sizeof *ret); // we want the size that is referenced by ret
    if (ret != NULL) { // you should check the return of malloc
        *ret = (A) {3, 2, 1};
        // or
        *ret = (A) { .a = 3, .b = 2, .c = 1 };
    }
    *a = ret;
}

另一個優點是任何未初始化的成員都歸零。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM