Reputation: 14649
Using this technique on a char *
pointer has worked for me . (Not show here, because there is no error with it). However, I'm passing a pointer to a pointer to the test_variadic
function.
Compiled with gcc -Wall -Wextra -Werror -Wpadded -std=c99 test.c -o test
I try to extract it with va_arg(args, int**)
, Then I'll de-reference the pointer to assign a value to it and I get this error:
test.c: In function ‘test_variadic’:
test.c:14:6: error: assignment makes pointer from integer without a cast [-Werror]
*aa = b++;
^
cc1: all warnings being treated as errors
#include <stdio.h>
#include <stddef.h>
#include <stdarg.h>
static int test_variadic(size_t length, ...)
{
int** aa;
int b = 4;
va_list args;
va_start(args, length);
for(size_t i = 0; i < length; i++) {
aa = va_arg(args, int**);
*aa = b++;
}
va_end(args);
return 0;
}
int main()
{
int* a, *b;
if(test_variadic(2, &a, &b) == 0) {
printf("%d %d\n", *a, *b);
}
return 0;
}
So basically what I'm trying to do is pass the function pointers to variables (in this case int
s), and then I want to assign those pointers to a value (from the function test_v*
. I'd like to be able to pass pointers to the function, and then assign a value to the pointers. I want to be able to assign a value that is not a pointer so that I can access it back in main.
Upvotes: 0
Views: 397
Reputation: 141598
The error is nothing to do with variadic lists; you are making a type mismatch. Your code is:
int **aa; // a points to a pointer-to-int
int b;
// .... make 'a' point somewhere
*aa = b; // error: (*aa) is a pointer-to-int, but you try to assign an int
Based on your post description, it seems you want to make *a
point somewhere that will find 4
.
Naively you might write *aa = &b; ++b;
however that will fail because b
is destroyed when the function returns. So you will have to allocate memory:
*aa = malloc( sizeof **aa );
if ( ! *aa )
return 1;
**aa = b++;
The main
function should then do free(a); free(b);
after printing the values.
Upvotes: 1