Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

c - I am trying to use pointers to change the values in a struct via a function, but I get an error when inputting adress the in the function

I have a program where I first create a typedef struct in an inluded .h file like so

typedef struct {
 uint16_t x, y;
 } vector_t;

I then create a structure according to above definition in my main like so

vector_t vec = {5,10};

And then try to use it in the following function

void initVector(vector_t *v) {
 (*v).x = 10;
 (*v).y = 20;  
}

I input my function surrounded by to print statements like so.

printf("%d %d
 innit 
",vec.x,vec.y);

void initVector(&vec);

printf("%d %d
 
",vec.x,vec.y);

However when I try to build the program I get the following error

expected declaration specifiers or '...' before '&' token

When the function is commented out, the print statements gives the vector, so I do not think that is the problem, but I cannot see why it should not work.

Any help would be appreciated

question from:https://stackoverflow.com/questions/65643451/i-am-trying-to-use-pointers-to-change-the-values-in-a-struct-via-a-function-but

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you want, is to call the function initVector, not to declare it, so you have to replace

void initVector(&vec);

with just

initVector(&vec);

BTW, in the function initVector, you can write:

void initVector(vector_t *v) 
{
    v->x = 10;
    v->y = 20;  
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...