Reputation: 586
I have a problem and I couldn't find any solution about this. In the example.h
I define the struct by this:
#define TOTAL_NUMBER 3
struct{
float FirstValue[TOTAL_NUMBER];
float LastValue[TOTAL_NUMBER];
} VALUES;
And I want to use in the example.c like this.
VALUES.FirstValue={1,2,3}
But I have an error. How can I use like this in the example.c ?
VALUES.FirstValue={1,2,3}
Upvotes: 1
Views: 70
Reputation: 213832
You can overwrite previous struct values and set individual members by using compound literals:
typedef struct{
float FirstValue[3];
float LastValue[3];
} VALUES;
int main()
{
VALUES v;
v = (VALUES) { .FirstValue = {1,2,3} };
}
This is similar to memset
all zeroes, followed by memcpy
.
Upvotes: -1
Reputation: 44274
Well, you can't.
The general syntax
SomeArrayVariable = {1,2,3};
is valid only as initialization - not as assignment.
Example:
int arr[3];
arr = {1, 2, 3}; // Error - invalid assignment
int arr[3] = {1, 2, 3}; // Fine - valid initialization
Instead you can do:
VALUES.FirstValue[0] = 1;
VALUES.FirstValue[1] = 2;
VALUES.FirstValue[2] = 3;
or you can do like:
struct{
float FirstValue[TOTAL_NUMBER];
float LastValue[TOTAL_NUMBER];
} VALUES = {{1, 2, 3}, {0, 0, 0}};
to make it an initialization.
That said.. it's more common to make a typedef'ed struct and then make instances of that type where you need it. This will also allow you to use initialization. Like:
#include <stdio.h>
#define TOTAL_NUMBER 3
typedef struct{
float FirstValue[TOTAL_NUMBER];
float LastValue[TOTAL_NUMBER];
} values_t;
int main(void) {
values_t values = {{1,2,3}, {0, 0, 0}};
printf("%f\n", values.FirstValue[1]);
printf("%f\n", values.LastValue[1]);
return 0;
}
Upvotes: 5
Reputation: 12732
You can't assign array as you do for normal variable.
But you can use memcpy
to copy the compound literals as below.
memcpy(VALUES.FirstValue, (float[]){1,2,3}, sizeof VALUES.FirstValue);
Upvotes: 1