Thread: Undefined array in struct

  1. #1
    Registered User
    Join Date
    Jan 2007
    Posts
    2

    Undefined array in struct

    Hi there.
    I am confused as to why the following piece of code does work:

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    struct my_struct
    {
           char my_word[];
           int num;
    };
           
    int main()
    {
       
        struct my_struct eg;
    
        eg.my_word[3] = 'y';
        eg.my_word[67] = 'w';
    
        printf("\n %c \n %c \n %c \n", eg.my_word[3], eg.my_word[67], eg.my_word[54]);
        
        system("pause");
    }
    The array in the struct is not assigned a maximum size. Outside of a struct this is not allowed. This behaviour is not mentioned in my text book.
    Why is this?

    Many thanks,
    WVM

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    C99 Extension: Flexible array members.

    http://david.tribble.com/text/cdiffs.htm#C99-fam

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,794
    note that in this case my_word[3] overwrites some byte in the num member, and my_word[64] acesses some memory out of bounds...

    On some compilers it works, on some will crash
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

  4. #4
    Registered User
    Join Date
    Jan 2007
    Posts
    2
    Thanks guys.
    WVM

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Converting from C to C++
    By Taka in forum C++ Programming
    Replies: 5
    Last Post: 04-08-2009, 02:16 AM
  2. Replies: 1
    Last Post: 12-03-2008, 03:10 AM
  3. Fixing my program
    By Mcwaffle in forum C Programming
    Replies: 5
    Last Post: 11-05-2008, 03:55 AM
  4. How to: Use OpenGL with Jgrasp
    By Pickels in forum Game Programming
    Replies: 3
    Last Post: 08-30-2005, 10:37 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM