如何在C中的typdef结构中为数组赋值?

时间:2022-06-06 21:42:48

I am trying to assign values to an array within a typedef struct and continually am getting an syntax error.

我试图将值赋给typedef结构中的数组,并不断得到语法错误。

Error expected '=', ',', ';', 'asm' or '__attribute__' before '.' token

Here is my code:

这是我的代码:

myfile.h

#define  Digit12  0x00u
#define  Digit34  0x01u
#define  Digit56  0x01u

typedef struct
{
   uint8_t trData[3]; 
} CImageVersion;

myfile.c

CImageVersion oImageVersion; // declare an instance

oImageVersion.trData = { Digit12, Digit34, Digit56};

Later on in the code

稍后在代码中

otherfile.c

extern CImageVersion oImageVersion;

An arry is a pointer but if i change the assignment to

arry是一个指针,但如果我将赋值更改为

oImageVersion->trData = { Digit12, Digit34, Digit56};

I get the same error. I am very confused as to what I am doing wrong The error is pointing to directly after the oImageVersion when I assign the values

我犯了同样的错误。关于我做错了什么我很困惑当我分配值时,错误指向oImageVersion后面的错误

1 个解决方案

#1


3  

You can't assign directly to an array. The syntax you're using is only valid when a variable is defined. I.e. you can do this:

您无法直接分配给数组。您使用的语法仅在定义变量时有效。即你可以这样做:

CImageVersion oImageVersion = { { Digit12, Digit34, Digit56} };

But not this:

但不是这个:

CImageVersion oImageVersion;
oImageVersion.trData = { Digit12, Digit34, Digit56};

If you don't assign the values when the variable is defined, you need to assign to each array element individually:

如果在定义变量时未分配值,则需要分别为每个数组元素分配:

oImageVersion.trData[0] = Digit12;
oImageVersion.trData[1] = Digit34;
oImageVersion.trData[2] = Digit56;

#1


3  

You can't assign directly to an array. The syntax you're using is only valid when a variable is defined. I.e. you can do this:

您无法直接分配给数组。您使用的语法仅在定义变量时有效。即你可以这样做:

CImageVersion oImageVersion = { { Digit12, Digit34, Digit56} };

But not this:

但不是这个:

CImageVersion oImageVersion;
oImageVersion.trData = { Digit12, Digit34, Digit56};

If you don't assign the values when the variable is defined, you need to assign to each array element individually:

如果在定义变量时未分配值,则需要分别为每个数组元素分配:

oImageVersion.trData[0] = Digit12;
oImageVersion.trData[1] = Digit34;
oImageVersion.trData[2] = Digit56;