1

Is there a way to define an array inside a function argument in C? Something like this:

void arraysomething(double vec[2]){
    //do something...
}

int main(){
    arraysomething({1.,2.});
    return 0;
}

I searched all over the place and found nothing.

2
  • 3
    C is a distinct language from C++. If the question is about C, the C++ tag is not appropriate. Commented Jun 11, 2018 at 19:12
  • 1
    It looks like you want compound literals. Commented Jun 11, 2018 at 19:13

1 Answer 1

5

What you're looking for is called a compound literal:

arraysomething((double []){1.,2.});

The syntax looks like an initializer for an array or struct preceeded by what looks like a cast to the type in question.

Because you want to pass in array, the typename given should be double [], which means an array of unspecified size. The actual size isn't needed because it is inferred from the number of elements in the literal.

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

3 Comments

i got this message: stokes.c: In function 'main': stokes.c:312:30: warning: excess elements in scalar initializer dotproduct2(A, (double){1.,2.}); ^~ stokes.c:312:30: note: (near initialization for '(anonymous)') stokes.c:312:18: error: incompatible type for argument 2 of 'dotproduct2' dotproduct2(A, (double){1.,2.}); ^ stokes.c:45:8: note: expected 'double *' but argument is of type 'double' double dotproduct2(double A[2], double B[2]){
@JoãoPauloAndrade I made an edit. It should be (double []), not (double).
@JoãoPauloAndrade Glad I could help. Feel free to accept this answer if you found it useful.

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.