简体   繁体   English

C中结构体数组变量的初始化与声明

[英]Initialization and declaration of array variable of a structure in C

I am getting an error while trying to compile this code.......tried different IDEs我在尝试编译这段代码时遇到错误......尝试了不同的 IDE

#include<stdio.h>
#include<stdlib.h>
struct car{
        int price[5];
    }c1;
int main(){
    c1.price[5]={10,20,30,40,50};
}

error:错误:

7 14 D:\CODING\c programs\Struct.c [Error] expected expression before '{' token 7 14 D:\CODING\c programs\Struct.c [错误] '{' 标记前的预期表达式

This isn't valid C. You can only statically initialize an array at definition time.这无效 C。您只能在定义时静态初始化数组。 Something like the following:像下面这样的东西:

int price[5] = {10,20,30,40,50};

Otherwise, you must use subscripts to initialize the array:否则,您必须使用下标来初始化数组:

c1.price[0] = 10;
c1.price[1] = 20;
c1.price[2] = 30;
c1.price[3] = 40;
c1.price[4] = 50;

Try to read the book 'The C Programming language by Ritchie & Kernighan' to get a feel for the language first.尝试阅读“Ritchie & Kernighan 编写的 C 编程语言”一书,首先感受一下这门语言。

After this declaration在这个声明之后

struct car{
    int price[5];
}c1;

the object c1 with its data member are already created that is defined.已定义的 object c1及其数据成员已创建。

So in this statement所以在这个声明中

c1.price[5]={10,20,30,40,50};

you are trying to assign a braced list to the non-existent element of the array with the index equal to 5 .您正在尝试将大括号列表分配给索引等于5的数组中不存在的元素。

Even if you will write instead即使你会写

c1.price = {10,20,30,40,50};

nevertheless arrays do not have the assignment operator.然而 arrays 没有赋值运算符。

You can initialize the data member price of the object c1 when the object is defined.定义object时,可以初始化object c1的数据成员price For example例如

struct car{
    int price[5];
}c1 = { .price={10,20,30,40,50} };

Otherwise to change values of the data member price you should use a loop as for example否则要更改数据成员价格的值,您应该使用循环作为示例

for ( size_t i = 0; i < sizeof( c1.price ) / sizeof( *c1.price ); i++ )
{
    c1.price[i] = ( int )( 10 * ( i + 1 ) );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM