3

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

}
indiv
  • 17,306
  • 6
  • 61
  • 82
user968000
  • 1,765
  • 3
  • 22
  • 31
  • Look at the first answer to the question I linked. You're trying to use the syntax for initialization when you're doing an assignment which won't work. – jpw Nov 21 '14 at 00:11

4 Answers4

5

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.

Alex Celeste
  • 12,824
  • 10
  • 46
  • 89
1

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

thurizas
  • 2,473
  • 1
  • 14
  • 15
  • memset is **dangerous** function! Some slowly but safely in this way > **obj = Obj_Type{}**; – Redee Nov 08 '21 at 18:11
1

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.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
-2

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}};
Kaizhe Huang
  • 990
  • 5
  • 11