Undefined array in struct

This is a discussion on Undefined array in struct within the C Programming forums, part of the General Programming Boards category; 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 ...

  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

    ╔╗╔╦══╦╗╔╦══╦╗
    ║╚╝║╔╗║╚╝║╔╗║║
    ║╔╗║╠╣║╔╗║╠╣╠╣
    ╚╝╚╩╝╚╩╝╚╩╝╚╩╝

    codez http://code.google.com/p/zxcvbn/

  3. #3
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,456
    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
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  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, 02:10 AM
  3. Fixing my program
    By Mcwaffle in forum C Programming
    Replies: 5
    Last Post: 11-05-2008, 02: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21