简体   繁体   English

如何仅在5个位置的数组中初始化第4个位置

[英]How to initialize 4th position only in Array of 5 positions

I wanted to store 10 in 4th position of array of 5 positions. 我想将10存储在5个位置的数组的第4个位置中。 How to do ? 怎么做 ?

int main( ) 
{  
    int a[5] = {,,,,4} ;
    return 0; 
}

If i do that i get error. 如果我这样做,我会出错。 Please help. 请帮忙。

Thanks in advance. 提前致谢。

You can't do it with initialization, but you can leave the data uninitialized and then assign to the one you care about: 您无法通过初始化来做到这一点,但可以保留未初始化的数据,然后将其分配给您关心的数据:

int a[5]; a[3] = 10;

I'm not sure why you'd want to do this, but that's a whole separate question... 我不确定为什么要这样做,但这是一个单独的问题...

Edit: I should add that in C99, you can use initialization: 编辑:我应该在C99中添加它,您可以使用初始化:

int a[4] = { [3]=10 };

This is called designated initialization. 这称为指定初始化。

I'm assuming that when you say "4th position" you mean array index = 4 (which is actually the fifth position). 我假设当您说“第四位置”时,您的意思是数组索引= 4(实际上是第五位置)。 If it really needs to be done in one line: 如果确实需要一行完成:

int main()
{
    int a[5] = { a[0], a[1], a[2], a[3], 10 };
    return 0;
}

This compiles and runs without warnings or errors with gcc -Wall -O0 . 使用gcc -Wall -O0编译并运行时不会出现警告或错误。 Compiling with optimisation enabled, eg gcc -Wall -O3 , generates warnings, eg 在启用优化的情况下进行编译,例如gcc -Wall -O3 ,生成警告,例如

foo.c:3: warning: ‘a[0]’ is used uninitialized in this function

but it still compiles and runs without error. 但它仍然可以编译并运行而没有错误。

只需将其他元素显式设置为0

int a[5] = {0,0,0,0,10} ;

If you're using C99, you can use a feature called designated initializers to initialize particular array elements. 如果使用的是C99,则可以使用称为指定的初始化程序的功能来初始化特定的数组元素。 In this case, you would do this: 在这种情况下,您可以这样做:

int a[5] = { [4] = 4 };

which initializes the element at index 4 to 4, and all of the other elements to 0. 这会将索引4处的元素初始化为4,并将所有其他元素初始化为0。

GCC also provides this feature as an extension to the C language, but keep in mind this is not valid ISO C90, nor is it valid in C++. GCC还提供了此功能, 作为对C语言的扩展 ,但请记住,这不是有效的ISO C90,也不在C ++中有效。 It is valid in C99 only. 仅在C99中有效。

I suppose you can use placement new. 我想您可以使用新的展示位置。

int arr[4]; //uninitialized
new (&arr[3]) int(10); //"initializes"

I don't think you can have an "uninitialized" int in C. This looks like it should give a compiler error. 我不认为您可以在C中使用“未初始化”的int 。这看起来应该会产生编译器错误。

I think you will have to use: 我认为您将必须使用:

int main( ) 
{  
    int a[5] = {0,0,0,0,4} ;
    return 0; 
}

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

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