Search code examples
arrayscinitializationdeclaration

Is there any way to initialize an array without brackets?


I have the question if there is any way to initialize an array with multiple elements without brackets, for example:

int a[5] = {1,2,3,4,5};

Since *(a + 5) equals with a[5] , why i cannot initialize with:

int *(a + 5) = {1,2,3,4,5};

it gives me the error: expected ')' before '+' token.


Solution

  • This

    int *(a + 5) = {1,2,3,4,5};
    

    just is an invalid declaration because in the parentheses there is used the expression ( a + 5 ) with an entity named a that was not declared.

    Without using square brackets you could write for example

    typedef int T[5];
    
    T a = { 1, 2, 3, 4, 5 };
    

    As for this your statement

    Since *(a + 5) equals with a[5] , why i cannot initialize with:

    then in this context *( a + 5 ) is not an array. It is an expression that yields an element a[5] provided that a was already declared as an array with the number of elements not less than 6. Otherwise a[5] will be a non-existent element of the array a.