How can I set structure members using a single line of code?
typedef struct {
int x;
int y;
}test;
test obj[2];
int main()
{
obj[0].x=0; //this works
obj[0].y=0; //this works
obj[0]={0,0}; //compilation error
}
How can I set structure members using a single line of code?
typedef struct {
int x;
int y;
}test;
test obj[2];
int main()
{
obj[0].x=0; //this works
obj[0].y=0; //this works
obj[0]={0,0}; //compilation error
}
Structs can be assigned to with the =
operator, exactly the same way as any other value in C:
obj[0] = existing_test;
obj[1] = function_returning_test();
The above rely on struct values that have themselves come from somewhere else in the program (possibly having been initialized in multiple statements like in the question); to create a struct value in a single expression, use the object literal syntax:
obj[0] = (test){ .x = 15, .y = 17 };
obj[1] = (test){ .y = 19 };
Any fields left out of a such a literal are still present, but set to the appropriate zero value for their type, so in the above example obj[1].x
is set to zero.
If you are looking to set the values to zero, the following line of code should work:
memset(&obj,0,sizeof(obj));
However, it is only going to work if you want the values initialized to zero
You can only initialize all values in your array of structs in a single line of code when the instance is created. (not including use of memset
). Consider the following example:
#include <stdio.h>
typedef struct {
int x;
int y;
} test;
int main()
{
test obj[2] = { { 3, 5 }, { 4, 6 } };
int i = 0;
for (i = 0; i < 2; i++)
printf ("\n obj[%d].x = %d obj[%d].y = %d\n", i, obj[i].x, i, obj[i].y);
return 0;
}
output:
obj[0].x = 3 obj[0].y = 5
obj[1].x = 4 obj[1].y = 6
Note: normal initialization is to 0
, but different values were used to illustrate the point.
I don't think you can assign a structure value to a structure variable. Think of obj[0]
is some address of memory.
But you can do it during array of structure initialization:
test obj[2] = {{0, 0}, {1, 1}};