Home > Blockchain >  Problems of shifting pointers of list of structs in function in C/C
Problems of shifting pointers of list of structs in function in C/C

Time:06-20

There's a code like that:

typedef struct {
    int a;
    int b;
}x;

int func(x *data){
    ...
    *(data   1)->a = 3; // This will cause an error
    ...
}

int main(){
    x data[3];
    func(&data);
}

How can I access to a specific element in list of structs in function correctly?

CodePudding user response:

The quick fix would be something like this:

int func(x *data){
    (data   1)->a = 3;  // writes 3 to `a` member variable of second item in the passed-in array
    return 0;
}

int main(){
    x data[3];
    func(data);  // note that no & is required here
}

... but a better fix might be to change func() to expect a simple pointer-to-x as its argument, rather than a pointer-to-array-of-x's, and then pass in a pointer to the x you want changed directly, instead, like this:

int func(x *data){
    data->a = 3; // write 3 to into the passed-in x-object
    return 0;
}

int main(){
    x data[3];
    func(&data[1]);  // pass in a pointer to the second item in the array
}

CodePudding user response:

typedef struct {
    int a;
    int b;
}x;

int func(x *data){
    *(data   1)->a = 3; // This will cause an error
}

int main(){
    x data[3];
    func(&data);
}

Compiling that code gives:

<source>: In function 'int func(x*)':
<source>:7:5: error: invalid type argument of unary '*' (have 'int')
    7 |     *(data   1)->a = 3; // This will cause an error
      |     ^~~~~~~~~~~~~~
<source>:8:1: warning: no return statement in function returning non-void [-Wreturn-type]
    8 | }
      | ^
<source>: In function 'int main()':
<source>:12:10: error: cannot convert 'x (*)[3]' to 'x*'
   12 |     func(&data);
      |          ^~~~~
      |          |
      |          x (*)[3]
<source>:6:13: note:   initializing argument 1 of 'int func(x*)'
    6 | int func(x *data){
      |          ~~~^~~~
Compiler returned: 1

There is so much wrong with this code that you better start over writing modern C code instead of C code disguised as C . Don't use C-style arrays. Use std::array or std::vector:

#include <array>
#include <vector>

struct  X {
    int a;
    int b;
};

void func(std::array<X, 3> &data){
    data[1].a = 3;
}

void func2(std::vector<X> &data){
    data.emplace_back(3, 4);
}

int main(){
    std::array<X, 3> data;
    func(data);

    std::vector<X> data2;
    func2(data2);
}
  •  Tags:  
  • c
  • Related