2

I have 2 parts to this question.

1: If I want to pass a const int array to a function, normally I would do so.

const int array[3] = {1,2,3};
somefunction(array,3);

But I want to do it in a simpler way like you can do with strings is this possible.

somefunction("abc",3);

To something like somefunction({1,2,3},3); I know this doesn't work but is there a syntactically correct way to do this.

2: If the previous question is possible then this one is answered. Is there a way to mix ascii values in a const string. like... somefunction({1,2,3,"test"},7); I know this doesn't work but is there a syntactically correct way to do this.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Jesse Taube
  • 402
  • 3
  • 11
  • The above duplicate post is for the first question. I believe the answer to the second one is no, it can't be done. Arrays in C cannot have elements with different types. – kaylum Apr 05 '20 at 21:06

1 Answers1

2

Answering the first your question i can say you can do it using the compound literal.. For example

#include <stdio.h>

void f( const int a[], size_t n )
{
    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );
}

int main(void) 
{
    f( ( int[] ) { 1, 2, 3 }, 3 );
}

But you can not have an array with elements of different types.

So for such a construction {1,2,3,"test"} you need to split the string literal into separate characters like {1,2,3, 't', 'e', 's', 't'}

Eraklon
  • 4,206
  • 2
  • 13
  • 29
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335