开发者

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

I wanted to store 10 in 4th position of array of 5 positions. How to do ?

开发者_C百科
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:

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

This is called designated initialization.


Just explicitly set the other elements to 0.

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


I'm assuming that when you say "4th position" you mean array index = 4 (which is actually the fifth position). 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. Compiling with optimisation enabled, e.g. gcc -Wall -O3, generates warnings, e.g.

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

but it still compiles and runs without error.


I suppose you can use placement new.

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


If you're using C99, you can use a feature called designated initializers to initialize particular array elements. 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.

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++. It is valid in C99 only.


I don't think you can have an "uninitialized" int in C. This looks like it should give a compiler error.

I think you will have to use:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜