This is my code:
#include <stdio.h>
void add(int num, ...);
int main(void)
{
int a=100, b=200, c=300;
add(1, a);
add(2, a, b);
add(3, a, b, c);
return 0;
}
void add(int num, ...)
{
int *p=NULL;
p=&num+1;
printf("%x \n", p);
if(num==1)
{
printf("%d \n", p[0]);
printf("num is: %d \n", num);
}
else if (num==2)
{
printf("%d \n", p[0]+p[1]);
printf("num is: %d \n", num);
}
else
{
printf("%d \n", p[0]+p[1]+p[2]);
printf("num is: %d \n", num);
}
}
From my understanding, p initially points to a, which is 10. Thus, it should print 10, 30, 60, respectively. Nonetheless, it prints
6786db50
1736891264
num is: 1
6786db50
1736924031
num is: 2
6786db50
1867401241
num is: 3
Is p pointing to a wrong address? How can I correctly read the arguments passed as ...?
That’s not how you use variadic function calls, you need to use the
va_*function calls to extract the parameters.See http://unixhelp.ed.ac.uk/CGI/man-cgi?stdarg+3 or http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_C.2C_Objective-C.2C_C.2B.2B.2C_and_D