#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Posts
    8
    Rep Power
    0

    dynamically creating a struct (assigning size problem)


    Hi,

    I've got a function (makeTransArray) that dynamically creates an array of structs, whose size is determined by another function (scanner), which calls makeTransArray.

    Code:
    void makeTransArray(int n)
    {
    	struct Transaction transAll[n]; //create an array to hold n transactions
    }
    The compiler keeps moaning about transAll[] having an unknown size. The exact error messages are:

    error C2057: expected constant expression
    error C2466: cannot allocate an array of constant size 0
    error C2133: 'transAll' : unknown size
    warning C4047: '!=' : 'int' differs in levels of indirection from 'void *'
    I've had to create a dedicated function for this process because ANSI C does not allow me to declare data types in the middle of functions, however, it seems like it doesn't even like assigning a variable to a struct's size. I've tried changing the formal parameter of makeTransArray() to a const int, but that doesn't help.

    Is this the way to dynamically create data types such as structs?

    Thanks.
  2. #2
  3. not a fan of fascism (n00b)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Feb 2003
    Location
    ct
    Posts
    2,756
    Rep Power
    95
    use a pointer instead, and allocate a block of structures.
    struct Transaction *transAll; //create an array to hold n transactions

    if( (transall = calloc(n, sizeof(struct Transaction))) == NULL)
    //handle errors
  4. #3
  5. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,110
    Rep Power
    1803
    1) Variable length arrays are supported in C99 but not C89. I guess your compiler is not C99 compliant in this respect.

    2) An array declared like that will go out of scope when the function returns, and will not exist (the memory it uses will be available for re-use by other functions). You need to allocate it dynamically using malloc(), calloc(), or new for example. Alternatively you ould declare it as static, but then it would by definition be fixed size.

    3) Even where supported, and scope ere not a problem, creating large arrays of unspecified length on the stack is a bad idea, as the stack is a limited resource.

    Clifford
  6. #4
  7. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Posts
    8
    Rep Power
    0
    The advice has been very helpful. After reading more on malloc, it is definitely a more efficient and cleaner way of dynamically creating data structures.

IMN logo majestic logo threadwatch logo seochat tools logo