Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "int *a = (int[2]){0, 2};" exactly do?

Tags:

c

I was very surprised when I saw this notation. What does it do and what kind of C notion is it?

like image 216
Dpp Avatar asked Jun 11 '10 14:06

Dpp


People also ask

What does int a 2 mean?

It defines a width of a bitfield in a struct. A bitfield holds an integer value, but its length is restricted to a certain number of bits, and hence it can only hold a restricted range of values.

What does New in Int Myarray new int n do?

new allocates an amount of memory needed to store the object/array that you request. In this case n numbers of int. The pointer will then store the address to this block of memory.


1 Answers

This is a compound literal as defined in section 6.5.2.5 of the C99 standard.

It's not part of the C++ language, so it's not surprising that C++ compilers don't compile it. (or Java or Ada compilers for that matter)

The value of the compound literal is that of an unnamed object initialized by the initializer list. If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

So no, it won't destroy the stack. The compiler allocates storage for the object.

Parenthesis are put around the type and it is then followed by an initializer list - it's not a cast, as a bare initialiser list has no meaning in C99 syntax; instead, it is a postfix operator applied to a type which yields an object of the given type. You are not creating { 0, 3 } and casting it to an array, you're initialising an int[2] with the values 0 and 3.


As to why it's used, I can't see a good reason for it in your single line, although it might be that a could be reassigned to point at some other array, and so it's a shorter way of doing the first two lines of:

int default_a[] = { 0, 2 };
int *a = default_a;

if (some_test) a = get_another_array();

I've found it useful for passing temporary unions to functions

// fills an array of unions with a value
kin_array_fill ( array, ( kin_variant_t ) { .ref = value } )
like image 151
Pete Kirkham Avatar answered Sep 27 '22 18:09

Pete Kirkham