Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ va_list not returning arguments properly

I have a problem with using va_list. The below code works for an int:

main() {
  int f1=1;
  float** m = function(n,f1);
}

float** function(int n,...) {

  va_list mem_list;
  va_start(mem_list, n);
  for (int i=0;i<n;i++) {
    for (int j=0;j<n;j++) {
      //m[i][j]=va_arg(mem_list,float);
      int f = va_arg(mem_list,int);
      printf("%i \n",f);
    }
  }

  va_end(mem_list);
  return NULL;
}

However when I change to a float i.e.

float f1=1.0;
float f = va_arg(mem_list,float);
printf("%f \n",f);

It does not return the right value (the value is 0.00000). I am extremely confused at what is happening.

like image 957
user1422573 Avatar asked Dec 27 '22 23:12

user1422573


1 Answers

In the context of a varargs call, float is actually promoted to double. Thus, you'll need to actually be pulling doubles out, not floats. This is the same reason that %f for printf() works with both float and double.

like image 77
FatalError Avatar answered Jan 09 '23 13:01

FatalError