Thread: flexible array member not at end of struct

  1. #1
    Lode Runner
    Join Date
    May 2004
    Posts
    53

    flexible array member not at end of struct

    in a struct, I would have an array of size [][3], where [] is undefined. But it won't work :

    example

    Code:
    struct foo {
        int bar[][3];
    };
    I get :

    Code:
     11: error: flexible array member not at end of struct
    I can't use
    Code:
    int *bar[3];
    cause then I have bar[3][].

    Anyone ?... Anyone ?

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    The size of the array must be known at compile time. So, either go with a fixed array size:
    int foo[10][3];
    or go with an array of pointers and malloc the memory later on.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Lode Runner
    Join Date
    May 2004
    Posts
    53
    OK, so what would the malloc line look like ?

    Code:
    myFoo.bar=malloc(3*size*sizeof(int));
    or should I make two mallocs (one for *(myFoo.bar) and one for myFoo.bar) ? though I don't know how to write the first one.

    pointers and memory management are still fuzzy to me

  4. #4
    Lode Runner
    Join Date
    May 2004
    Posts
    53
    OK, I'm advancing here. I have my struct now like this
    Code:
    struct foo {
          int **bar;
          int **bar2;
    }
    and it works in most cases.

    the problem is I want to use a foo as a global variable. But I can't if I don't give the entries to the struct. and bar2 is not easy stuff. I have a big function to calculate bar2's entries. I can't just write them down.

    Any ideas on how to handle this ?

  5. #5
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    555
    You want to make a variable of type struct foo, global or foo itself? just declare it outside of any functions (and above them)

  6. #6
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Which compiler are you using?


    Code:
    struct foo {
        int a;
        int bar[][3];
    };
    compiles it just fine with
    gcc -std=c99 prog.c



    Bear in mind that it is wrong to have a struct consisting only of a flexible array
    Commenting out the int a; causes gcc to report
    flexible array member in otherwise empty struct
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    Lode Runner
    Join Date
    May 2004
    Posts
    53
    I toyed around for a while with what you guys told me, understood some important I am sillyI am sillyI am sillyI am silly, learned a few tricks, and finally, when I thought everything was going to work I have some new stupid problems.

    first of all :
    compiles it just fine with
    gcc -std=c99 prog.c
    doesn't work, I get the same goddamn errors. I guess it the BSD kernel or something, security issues maybe.

    Next, i still have my struct but this time I'm trying to mallocate it.
    Code:
    struct foo {
          int **bar;
    }
    Everything compiles nicely with this, but when I try to declare a foo type global variable in the main program with this line :
    Code:
    struct foo *myFoo = malloc(12*sizeof(int));
    I get :
    Code:
    error: initializer element is not constant
    I put (12*sizeof(int)) thinking of bar being 4x3...

  9. #9
    Registered User
    Join Date
    May 2004
    Posts
    127
    >error: initializer element is not constant
    You can't call malloc outside of a function. Global initializers must be constant.
    When writing a specialization, be careful about its location; or to make it compile will be such a trial as to kindle its self-immolation.

  10. #10
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    I think this is what you're trying to do:
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    struct foo
    {
    	int (* bar)[3]; /* Declares a pointer to an int array[3] */
    };
    
    struct foo myFoo;
    
    int main(void)
    {
    	int i, j;
    	int k = 0;
    
    	/* Allocate memory for myFoo.bar */
    	myFoo.bar = malloc(4 * sizeof(*myFoo.bar));
    
    	/* Check success of memory allocation */
    	if (myFoo.bar == NULL)
    	{
    		fprintf(stderr, "Out of memory\n");
    		return EXIT_FAILURE;
    	}
    
    	/* Sample usage of myFoo.bar */
    
    	for (i = 0;i < 4;i++)
    		for (j = 0;j < 3;j++)
    			myFoo.bar[i][j] = k++;
    
    	for (i = 0;i < 4;i++)
    		for (j = 0;j < 3;j++)
    			printf("myFoo.bar[%d][%d] = %d\n", i, j, myFoo.bar[i][j]);
    
    
    	/* Use myFoo in the rest of your program as needed. */
    
    	getchar();
    	return EXIT_SUCCESS;
    }
    Note especially the method of declaring a pointer to an int array[3]. This is covered in more detail in "Chapter 8: Pointers to Arrays" at the site Hammer linked to.
    Last edited by anonytmouse; 05-14-2004 at 06:48 AM.

  11. #11
    Lode Runner
    Join Date
    May 2004
    Posts
    53
    YES ! PERFECT ! THANK YOU !

    I guess you guys spent a whole lot of time coding in C

    I've got to get used to thinking like this.

    Well, thanks a lot everyone.

  12. #12
    Lode Runner
    Join Date
    May 2004
    Posts
    53
    not so perfect,

    I can only fill the first row of bar. when I start putting some stuff in myFoo.bar[1][0], I get a Bus Error.

    Can anyone explain ?


    actually your code works but mine (the real one, not the example) doesn't. I'll check this a little further.
    Last edited by krappa; 05-14-2004 at 11:09 AM.

  13. #13
    Lode Runner
    Join Date
    May 2004
    Posts
    53
    I'd changed the .c but not the .h

    Some days I really loathe myself.

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    I dunno if this is what you're trying to do - you keep changing between arrays and pointers.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct foo {
        char name[20];  // 20
        int a;          // 4
        int bar[][3];   // 12*n
    };
    
    int main()
    {
        struct foo *jobber;
        size_t  alloc;
        int     i, j;
    
        printf( "%u\n", sizeof *jobber );
        printf( "%u\n", sizeof jobber->a );
        printf( "%u\n", sizeof jobber->bar[0] );
        
        // put a bar[10][3] at the end of the structure
        alloc = sizeof *jobber + sizeof jobber->bar[0] * 10;
        printf( "allocating %u bytes\n", alloc );
    
        jobber = malloc( alloc );
        strcpy( jobber->name, "hello" );
        jobber->a = 123;
        for ( i = 0 ; i < 10 ; i++ ) {
            for ( j = 0 ; j < 3 ; j++ ) {
                jobber->bar[i][j] = i * j;
            }
        }
        return 0;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. for loop with sort issues
    By redmondtab in forum C Programming
    Replies: 10
    Last Post: 10-09-2006, 10:36 AM
  2. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. memory allocation for flexible array member of struct
    By jcarouth in forum C Programming
    Replies: 3
    Last Post: 09-11-2005, 12:19 PM
  5. Inserting new member into array of structs
    By cathym in forum C Programming
    Replies: 6
    Last Post: 04-17-2005, 07:10 AM