Home > Net >  C - How to initialize new array inside functions parameter when calling it
C - How to initialize new array inside functions parameter when calling it

Time:08-05

void someVoid(int val[]){
    //doing something with val...
}

int main(){
    someVoid(???);
}

I am not sure how to call function, without declaring variable first, outside function parameters, in c

In c# this would be like this

static void Main(string[] args){
    someVoid(new int[]{...});
}

This would be convenient when calling function where you would need to insert dimensions or coordinates

CodePudding user response:

You can (maybe) do:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

static void
print_ints(int *x, size_t s)
{
    while( s-- ){
        printf("%d\n", *x  );
    }
}

int
main(int argc, char **argv)
{
    int explicit[] = {1, 2, 3};
    print_ints((int[]){1, 2, 3}, 3);
    print_ints(explicit, sizeof explicit / sizeof *explicit);
    return 0;
}

but I would argue that you shouldn't. In the above example, it takes one extra line of code to explicitly declare and initialize the variable. At most, any function you call will "save" one line of code per variable used. However, note the fragility of the hard-coded '3' in the first call. You can avoid that particular issue by using a sentinel in the array, but that's certainly not always desirable. Having the explicit variable is (IMO) more readable. In addition, this is a newish language (mis)feature that will cause some confusion to a certain class of reader, and will generate compiler errors on some toolchains. YMMV

  • Related