Is there any way to initialize an array without brackets?

Viewed 459

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.

4 Answers

The equivalence of E1[E2] and *(E1 + E2) only applies to an expression. What you have is a declaration which has different syntax rules.

So you need to use this syntax:

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

Replacing a[5] with *(a + 5) does not work in declarations or definitions.

If you really want to avoid square brackets (to win a bet I assume), here are 2 contorted but standard complying solutions:

Using trigraphs: int a??(5??) = {1,2,3,4,5};

Using digraphs: int a<:5:> = {1,2,3,4,5};

More information can be found in Digraphs and Trigraphs.

You can even write a fragment that will compile on recent compilers where trigraphs are disabled and digraphs supported:

// trick: the comment spans to the next line if trigraphs are enabled
#define TRIGRAPHS_DISABLED  1 //??/
-1

#if TRIGRAPHS_DISABLED
int a<:5:> = {1,2,3,4,5};
#else
int a??(5??) = {1,2,3,4,5};
#endif

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.

You may try like this:

int *arr=(int*)malloc(5*sizeof(int));
for(int i=0;i<5;i++) {
    scanf("%d",&(*(arr+i)));
}    
or
int *arr=(int*)malloc(5*sizeof(int));
*(arr+0)=1;
*(arr+1)=2;
*(arr+2)=3;
*(arr+3)=4;
*(arr+4)=5;
Related