[英]C: pass to function an array of structure pointers to be reallocated dynamically each time
[英]How to pass as parameter an array of pointers to structure in c
我試圖傳遞一個指向結構的指針數組作為參數,以在函數中對其進行修改並在main()
打印修改后的值。
代碼是:
#include "stdio.h"
typedef struct testStruct_s {
int x;
int y;
} testStruct;
typedef testStruct typeTab[4];
void modify(typeTab tab)
{
printf("Before modification %d\n", tab[2].x);
tab[2].x = 3;
printf("Modified %d\n", tab[2].x);
}
int main()
{
typeTab tab[4];
tab[2]->x = 0;
printf("First %d\n", tab[2]->x);
modify(*tab);
printf("Second %d\n", tab[2]->x);
return 0;
}
我得到以下輸出:
First 0
Before modification 1719752944
Modify 3
Second 0
我不知道如何在modify()
獲取tab[2].x
的正確值,以及如何修改此值以在之后打印tab[2]->x = 3
。
對於我嘗試做的事情,需要使用typedef testStruct
。
typeTab
已經是一個數組,因此typeTab tab[4]
聲明一個數組數組。 這意味着tab[2]->x
與tab[2][0].x
,這不是您想要的。
不要添加額外的維度,然后相應地修改訪問權限。
typeTab tab;
tab[2].x = 0;
printf("First %d\n", tab[2].x);
modify(tab);
printf("Second %d\n", tab[2].x);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.