the source code: #include <stdio.h> #include <stdlib.h> typedef struct test_st { char *name; int num; } test_t;
static char * str[] = { "one", "two", "three", "four", "five", "six", "seven" }; char * get_rand_str () { char *s = str[rand () % (sizeof(str) / sizeof(str[0]))]; return s; } int main () { char * s [10] = {NULL}; int i = 0; test_t test_struct[]= { { .name = s[i] = get_rand_str(), .num = i++, }, { .name = s[i] = get_rand_str(), .num = i++, }, { .name = s[i] = get_rand_str(), .num = i++, }, { .name = s[i] = get_rand_str(), .num = i++, }, { .name = s[i] = get_rand_str(), .num = i++, }, }; printf ("i = %d\n", i); for (i = 0; i < sizeof (test_struct) / sizeof(test_struct[0]); i ++) { printf ("name `%s\' num \'%d\' s[%d] = `%s\'\n", test_struct[i].name, test_struct[i].num, i, s[i]); } return 0; } compiling with gcc4 smspc tmp # LANG=C LC_ALL=C gcc -Wall test_struct_array.c -g then run it i got unexpected result: smspc tmp # ./a.out i = 5 name `two' num '0' s[0] = `two' name `five' num '0' s[1] = `(null)' name `three' num '0' s[2] = `(null)' name `six' num '0' s[3] = `(null)' name `two' num '0' s[4] = `(null)' gcc -v Using built-in specs. Target: i686-pc-linux-gnu Configured with: /usr/tmpdir/portage/gcc-4.0.0.20050522/work/gcc-4.0.0/configure --enable-version-specific-runtime-libs --prefix=/usr --bindir=/usr/i686-pc-linux-gnu/gcc-bin/4.0.0-20050522 --includedir=/usr/lib/gcc/i686-pc-linux-gnu/4.0.0-20050522/include --datadir=/usr/share/gcc-data/i686-pc-linux-gnu/4.0.0-20050522 --mandir=/usr/share/gcc-data/i686-pc-linux-gnu/4.0.0-20050522/man --infodir=/usr/share/gcc-data/i686-pc-linux-gnu/4.0.0-20050522/info --with-gxx-include-dir=/usr/lib/gcc/i686-pc-linux-gnu/4.0.0-20050522/include/g++-v4 --host=i686-pc-linux-gnu --build=i686-pc-linux-gnu --disable-altivec --enable-nls --without-included-gettext --with-system-zlib --disable-checking --disable-werror --disable-libunwind-exceptions --disable-multilib --enable-java-awt=gtk --enable-languages=c,c++,objc,java,f95 --enable-shared --enable-threads=posix --enable-__cxa_atexit --enable-clocale=gnu Thread model: posix gcc version 4.0.0-20050522 (Gentoo 4.0.0.20050522) compiling with gcc34 got following result as expect: smspc tmp # LANG=C LC_ALL=C gcc -Wall test_struct_array.c -g smspc tmp # ./a.out i = 5 name `two' num '0' s[0] = `two' name `five' num '1' s[1] = `five' name `three' num '2' s[2] = `three' name `six' num '3' s[3] = `six' name `two' num '4' s[4] = `two' -- Summary: gcc generates wrong code Product: gcc Version: 4.0.1 Status: UNCONFIRMED Severity: normal Priority: P2 Component: c AssignedTo: unassigned at gcc dot gnu dot org ReportedBy: sunmoon1997 at gmail dot com CC: gcc-bugs at gcc dot gnu dot org GCC build triplet: i686-pc-linux-gnu GCC host triplet: i686-pc-linux-gnu GCC target triplet: i686-pc-linux-gnu http://gcc.gnu.org/bugzilla/show_bug.cgi?id=21749