C hard coding of array typedef struct

This is such a stupid question that he even disappoints. Please bear with me, I feel especially stupid about it today.

I have a library with a specific typedef structure. mostly:

typedef struct {int x; int y;} coords;

What I really wanted to do was declare in my header an array of variables from this:

coords MyCoords[];

(I recently switched it only to coords *MyCoords;, and then ran it MyCoords = new coords[4];)

and then in my init I would like to hardcode some values ​​in it.

MyCoords[] = {{0, 0}, {2, 2} etc. 

I have to be just the brain today, because it does not allow me to make any simple attachment, even something simple, for example MyCoords[0] = {0, 0}

. . . MyCoords[0] = {0, 0}. MyCoords[0].x = 0; MyCoords[0].y = 0, , . ..

+3
4

, , , . , . ++. , , , extern.

extern coords MyCoords[];

.cpp, , () - , , , :

coords MyCoords[] = {{1, 2}, {3, 4}, ... };

, , , std::vector:

std::vector< coords > MyCoords;

, ,

MyCoords.push_back( coords(1, 2) );
MyCoords.push_back( coords(3, 4) );
....

, , :

coords c[] = ....;
MyCoords.insert(MyCoords.end(), c, c + sizeof c / sizeof *c);

, C ++. , . , , "" . (, , , , , , ), , , 1. ++ , , , , ++.

, ,

MyCoords[0] = {0, 0}

:

-> Set LHS to RHS
-> -> LHS is a variable of type `coords`. Fine
-> -> RHS is... hmm, `{0, 0}`. What the heck is it??

, , . C99, ( 1999 .) .

MyCoords[0] = (coords){0, 0};

, , - coord . , ( C C99-, ++, C89 ), , .

+5

, . , :

coords MyCoords[] = {{0, 0}, {2, 2}};

MyCoords , , , :

extern coords MyCoords[];
+9

, , :

typedef struct coords {int x, int y};

is not a complete typedef declaration in C, since it does not give a name to this type, only for struct (struct tags are not in the same namespace as type names in the C standard). To make a typedef declaration valid, you must provide a name for the entire type struct coords {int x, int y}, as if you were declaring a variable of that type, for example:

typedef struct coords {int x, int y} coords;
+2
source

It should be:

typedef struct coords {int x, int y} coords;
coords MyCoords[] = {{0, 0}, {2, 2}, {3, 4}};
0
source

Source: https://habr.com/ru/post/1706835/


All Articles