Search code examples
cvariadic-functionsansi-c

How to print contents of va_list in ansi c


I am trying to print the contents of a va_list, I want to pass an array to it I am getting gibrish in return

int printVA(int num_args,...);

int main(int argc, const char * argv[])
{
    int numArgs = 3;
    int arr [3];
    arr[0]=183;
    arr[1]=184;
    arr[2]=15;
    printVA(numArgs,arr);

    return 0;
}




int printVA(int num_args,...){
    va_list arg_list;
    int my_arg;
    va_start(arg_list, num_args);

    for(int i = 0; i<num_args;i++){
        my_arg = va_arg(arg_list, int);
        printf("%d\n", my_arg);
    }
    va_end(arg_list);
    return 1;

}

this is what i get

1606416584
15
1606416584

Solution

  • You are calling it incorrectly, pass the arguments themselves, not an array of them:

    printVA(numArgs, arr[0], arr[1], arr[2]);
    

    or simply:

    printVA(numArgs, 183, 184, 15);
    

    On the other hand, if you really want to pass the array, va_list is not the right solution.