简体   繁体   中英

ANSI C (C89) <stdarg.h> Getting value from array using va_list

I am trying to print a value in an array, but cannot print the value as normal. Trying to learn up on macros using C89 only. Here is the code:

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

int getValues(int, ...);
int *myArr;

int getValues(int num_args, ...) {
   int val[num_args];
   va_list ap;
   int i;
   va_start(ap, num_args);
   for(i = 0; i < num_args; i++) {
      val[i] = va_arg(ap, int);
   }
   myArr = val;
   va_end(ap);
   return *val;
}

int main(void) {
  getValues(1,2,3,4);
  for(int i = 0; i < sizeof(myArr); ++i){
    printf("%d\n", myArr[i]);
  }
  printf("Values are %d\n", myArr[0]); // Want this to print 1
   return 0;
}

The posted code has several problems, comments inlined below.

int getValues(int num_args, ...) {
   int val[num_args];          // <--- variable-length arrays did not exist in C89, not until C99
   /*...*/
   myArr = val;                // <--- saves address of local array 'val' into global `myArr`
   /*...*/
}                              // <--- but `val` ceases to exist once the function returns

int main(void) {
  getValues(1,2,3,4);          // <--- missing first argument, presumably '4' for 'num_args'
  for(int i = 0;
      i < sizeof(myArr);       // <--- sizeof(myArr) == sizeof(int*) is not the array count
      ++i){
    printf("%d\n", myArr[i]);  // <--- `myArr` points to an array which no longer exists
  }
  /*...*/
}

The following is a possible rewrite with just the minimal modifications to make the code work.

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

int *getValues(int, ...);

int *getValues(int num_args, ...) {
   int *val = malloc(num_args * sizeof(int));
   if(val == NULL) return NULL;
   va_list ap;
   va_start(ap, num_args);
   int i;
   for(i = 0; i < num_args; i++) {
      val[i] = va_arg(ap, int);
   }
   va_end(ap);
   return val;
}

int main(void) {
  int *myArr = getValues(5, 1,2,3,4,5);
  if(myArr == NULL) { abort(); } // error
  for(int i = 0; i < 5; ++i){
    printf("%d\n", myArr[i]);
  }
  free(myArr);
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM