Home > Back-end >  Modifying array via variable arguments
Modifying array via variable arguments

Time:10-16

I'm trying to modify an array via variable arguments by passing values of va_arg to the array but for some reason it gives weird results, Here is the code:

#include <stdio.h>
#include <stdarg.h>

void get_args(double* args, int argc, ...);

void get_args(double* args, int argc, ...) {
    va_list argv;
    va_start(argv, argc);

    if (argc == 1) {
        args[0] = va_arg(argv, double);
    }
    else if (argc == 4) {
        for (int i = 0; i < argc; i  ) {
            args[i] = va_arg(argv, double);
        }
    }

    va_end(argv);
}

int main(void) {
    double args[4] = { 0, 0, 0, 0 };
    get_args(args, 4, 0, 1, 2, 3);

    for (int i = 0; i < 4; i  ) {
        printf("args[%d] = %f\n", i, args[i]);
    }
    
    return 0;
}

On Visual Studio (MSVC) it gives following:

args[0] = 0.000000
args[1] = 0.000000
args[2] = 0.000000
args[3] = -92559592143668871097826611732759620974286504571030640424648704.000000

On GCC it gives following:

args[0] = 0.000000
args[1] = 0.000000
args[2] = 0.000000
args[3] = 0.000000

Anyone knows what the mistake i done?

CodePudding user response:

The types of the variadic arguments don't match the type given to va_arg.

The arguments you're passing to get_args i.e. 0, 1, 2, 3 are all of type int, but you're using type double when you try to retrieve them with va_arg. This is a type mismatch which triggers undefined behavior.

Either pass arguments that have type double:

get_args(args, 4, 0.0, 1.0, 2.0, 3.0);

Or use int to pull the arguments off:

args[i] = va_arg(argv, int);
  • Related