1

I am trying to declare a pointer to a array of initialized ints at once(gcc 5.2.0, gnu99)

This is working

int a1[] = {1, 2, 3, 4, 5};
int (*a)[] = &a1;

I tried this and it isn't

int *why = (int p[2]) {1,2};

../src/gps/gps.c:399:18: error: expected ')' before 'p'
  int *why = (int p[2]) {1,2};
                  ^

int (*b)[5]= (int(*)[5])&({11,2,3,5,6});

../src/gps/gps.c:400:31: warning: left-hand operand of comma expression has no effect [-Wunused-value]
  int (*b)[5]= (int(*)[5])&({11,2,3,5,6});
                           ^
int (*cc)[] = &{1, 2, 3, 4, 5}
../src/gps/gps.c:402:17: error: expected expression before '{' token
  int (*cc)[] = &{1, 2, 3, 4, 5}
                 ^

What I miss here?

5
  • What errors do you get? Commented Mar 30, 2018 at 19:35
  • Just a shot in the dark, but does int (*a)[] = &{1, 2, 3, 4, 5} do anything? Commented Mar 30, 2018 at 19:37
  • You should show the code first then the error messages that the code causes. Commented Mar 30, 2018 at 19:38
  • What are you trying to do with this line of code: int *why = (int p[2]) {1,2};? This is not correct C syntax as the error message tells you. Commented Mar 30, 2018 at 19:39
  • It was just a answer from StackOverflow that supposed to work :) (some old thread) Commented Mar 30, 2018 at 19:41

1 Answer 1

1

Here's the proper way to define these:

int *why = (int [2]) {1,2};
int (*a)[5]= &((int []){11,2,3,5,6});

When you create a compound literal, you prefix it with what looks like a typecast.

The first line didn't work because you attempted to put a variable name inside of the cast, and the second line didn't work because you didn't put the cast immediately before the part in curly braces.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't think the second line needs the (int[]) cast.
@Code-Apprentice - It's not a cast, it's a compound literal expression. Without it, the initializer has no inherent meaning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.