1

I'm trying to pass an array of pointers to structure as parameter, to modify it in a function and to to print the modified value in main().

The code is:

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

And I got the following output:

First 0
Before modification 1719752944
Modify 3
Second 0

I don't know the way to get the correct value of tab[2].x in modify() and how to modify this value to print tab[2]->x = 3 after.

For what I try to do, it is required to use the typedef testStruct.

1
  • There is no "array of pointers to structure" in your code. Commented Nov 19, 2018 at 17:00

1 Answer 1

2

typeTab is already an array, so typeTab tab[4] declares an array of arrays. This means tab[2]->x is the same as tab[2][0].x, which is not what you want.

Don't add the extra dimension, then modify the access accordingly.

typeTab tab;

tab[2].x = 0;
printf("First %d\n", tab[2].x);
modify(tab);
printf("Second %d\n", tab[2].x);
Sign up to request clarification or add additional context in comments.

1 Comment

@user10675921 Glad I could help. Feel free to accept this answer if you found it useful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.