Reputation: 266
I have a small problem with a code written below. VS 2010 compiles it, runs and I get the predicted result. But when I tried to compile this code with Qt Creator I get this warning every time: "Expected token ')' got int". Yes, program will be run by Qt Creator, but the program will blow up. What's wrong with this code:
#include <stdio.h>
#include <stdarg.h>
#define ARR_SIZE 2
int **getAddresses(int amount, ...)
{
static int *arr[ARR_SIZE] = {};
va_list vl;
if(amount > 0)
{
va_start(vl, amount);
int i;
for(i = 0; i < amount; i++)
{
*(arr + sizeof(int) * i) = va_arg(vl, int*); //This one is highlighted by the Qt Creator.
}
va_end(vl);
return 0;
}
else
{
return arr;
}
}
int main(void)
{
int a = 3, b = 5;
getAddresses(ARR_SIZE, &a, &b);
printf("BEFORE: %d, %d\n", a, b);
int **res = getAddresses(0), i;
for(i = 0; i < ARR_SIZE; i++)
{
*(*(res + sizeof(int) * i)) += 5;
}
printf("AFTER: %d, %d\n", a, b);
return 0;
}
Thank you for your answers beforehand.
ADDED: Qt Creator highlights this line of code *(arr + sizeof(int) * i) = va_arg(vl, int*);
Furthermore Dev++ is able to run this code without any warning and errors or crushing.
GCC is able to compile it under Fedora linux 14:
[Admin@localhost testerprog]$ gcc tester.c -o tester
[Admin@localhost testerprog]$ ls
tester tester.c
[Admin@localhost testerprog]$ ./tester
BEFORE: 3, 5
AFTER: 8, 10
[Admin@localhost testerprog]$
GCC version is 4.5.1 20100924 (Red Hat 4.5.1-4)
Upvotes: 0
Views: 2894
Reputation:
va_start(vl, amount);
int i;
That's not C.
Definitions must occur before code.
VC running it's sort of C/C++ mode won't mind. A C-only compiler will object.
Upvotes: 0
Reputation: 70929
--- Edited, as the original post is a bit wrong, but the same line is likely the cause ---
Since the error specifically mentioned finding an int instead of a closing parenthesis, I would suspect the offending line is
*(arr + sizeof(int) * i) = va_arg(vl, int*);
And while your code is valid C / C++, I would reverse my suspicion that the VS compiler made a mistake, but offer a similar suspicion that the Qt compiler either
va_arg
references in some other qt_xxx
style wrapper to allow proper compiling in the QT framework.--- Original post follows ---
int is a keyword in C / C++ so you cannot use it as a variable safely. It seems that the line
*(arr + sizeof(int) * i) = va_arg(vl, int*);
asks for the value of the address held by a variable, int, not the value referenced by an int pointer. Odds are that the VS compiler's error checking isn't as robust, leading to silent acceptance of the error.
Upvotes: 1