[Haifux] Intermingled code and declarations and gcc
Ilya A. Volynets-Evenbakh
ilya at total-knowledge.com
Thu Sep 17 15:02:01 MSD 2009
First of all, C does not allow mixing code and declarations. Period.
Second, variable-size arrays aren't allowed by ANSI C either.
However, GCC does have an extension, which allows things like that.
What I'd do, is move the for loop in the second example into a separate
(perhaps static inline) function. Something like:
#include <stdio.h>
int count_arr(char *arr[])
{
int i;
for (i=0; arr[i]!=NULL; i++);
return i;
}
int main(int argc, char argv[])
{
char my_array[count_arr(argv)];
.....
}
Eli Billauer wrote:
> Hi,
>
>
> Yes, it's C. The problem occurred when going through the standard
> configure/make procedure for gphoto2-2.3.1, and I'm positive that the
> attempt to compile was with gcc (and it blew on this problem). The file
> is gp-params.c. The date on the file is December 2006 (so it should work
> with an old compiler).
>
>
> Obviously, some people managed to compile this. I wonder what their
> magic was.
>
> The problem is *not* that the size of the declared array depends on a
> runtime variable. This compiles and runs (using uninitialized memory,
> but who cares):
>
> #include <stdio.h>
> int main(int argc, char *argv[]) {
>
> char my_array[argc];
> printf("%d", my_array[0]);
> return 0;
> }
>
> This doesn't compile at all:
>
> #include <stdio.h>
> int main(int argc, char *argv[]) {
> unsigned int my_count;
>
> for (my_count=0; argv[my_count] != NULL; my_count++);
>
> char my_array[my_count];
> printf("%d", my_array[0]);
>
> return 0;
> }
>
> Ideas? I suppose this issue arises every now and then when compiling
> code written by wild programmers.
>
> Eli
>
> Orna Agmon Ben-Yehuda wrote:
>
>
>> Hi Eli,
>>
>> Is this C? You are defining an array with an unknown length at compile
>> time. It won't work anyhow, no matter what the value of the length var
>> is. You need a malloc there.
>>
>> Unless this is C++ with some overriding?
>>
>> Orna.
>>
>>
>>
>
>
>
--
Ilya A. Volynets-Evenbakh
http://www.total-knowledge.com
More information about the Haifux
mailing list