【问题标题】:How to pass as parameter an array of pointers to structure in c如何将指针数组作为参数传递给c中的结构
【发布时间】:2019-04-22 02:07:33
【问题描述】:

我正在尝试将指向结构的指针数组作为参数传递,在函数中对其进行修改并在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

【问题讨论】:

  • 您的代码中没有“指向结构的指针数组”。

标签: c arrays pointers structure


【解决方案1】:

typeTab 已经是一个数组,所以typeTab tab[4] 声明了一个数组数组。这意味着tab[2]->xtab[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);

【讨论】:

  • @user10675921 很高兴我能提供帮助。如果您觉得有用,请随时 accept this answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-24
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-25
  • 1970-01-01
相关资源
最近更新 更多