[OT] C-Frage
Florian Lohoff
flo at rfc822.org
Thu Feb 20 15:01:02 CET 2003
On Thu, Feb 20, 2003 at 10:11:55AM +0100, Jan-Benedict Glaw wrote:
> Hallo .*!
>
> ---------------------------
> #include <stdio.h>
> #include <stdlib.h>
> #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
>
> static unsigned char a[] = {
> "ASD"[1],
> "Hello"[3],
> };
Hier wird ein array unbestimmter groesse kreiert ...
D.h. in wirklichkeit ist doch a dann ein
char ** oder ?
Da das dingen "unbestimmt" in der groesse ist sollte
sizeof nicht funktionierten ...
> int
> main(int argc, char *argv[])
> {
> int i;
>
> for(i = 0; i < ARRAY_SIZE(a) - 1; i++)
> printf("%d - 0x%02x\n", i, a[i]);
>
> return EXIT_SUCCESS;
> }
> -----------------------------------
>
> Das Problem ist a[]. Wenn es so wie jetzt da steht, dann kompiliert's
> nicht:
> jbglaw at baerchen:~$ gcc test.c
> test.c:6: initializer element is not constant
> test.c:6: (near initialization for `a[0]')
> test.c:7: initializer element is not constant
> test.c:7: (near initialization for `a[1]')
>
> Packe ich a[] in eine Funktion (main() z.B.), dann wird das brav
> zugelassen (und der gcc optimiert auch netterweise "ASD" und "Hello"
> heraus). Um den Style einzuhalten (und die Daten nicht auf den Stack zu
> packen, das sind in der Realität nämlich 'nen paar Bytes mehr...) soll
> das Array aber gleich an den Anfang, und halt _nicht_ in eine Funktion
> hinein. Das Progrämmchen oben ist nur ein testcase - in Wirklichkeit
> werden die initializers von a[] durch Macros erzeugt (und sind viel
> länger), aber die Kurzfassung reicht da schon:-)
>
> Hat jemand dazu einen Tip für mich?
Ja
static char a[] = {
"Hallo",
"Du"
NULL,
};
[...]
for(i=0;a[i]!=NULL;i++)
printf("%s\n", a[i]);
[...]
--
Florian Lohoff flo at rfc822.org +49-5201-669912
Heisenberg may have been here.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
URL: <http://lug-owl.de/pipermail/linux/attachments/20030220/3b88c1ee/attachment.sig>
More information about the Linux
mailing list