October 10th, 2003, 07:40 PM
dynamically creating a struct (assigning size problem)
I've got a function (makeTransArray) that dynamically creates an array of structs, whose size is determined by another function (scanner), which calls makeTransArray.
The compiler keeps moaning about transAll having an unknown size. The exact error messages are:
void makeTransArray(int n)
struct Transaction transAll[n]; //create an array to hold n transactions
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?
October 10th, 2003, 09:14 PM
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)
October 11th, 2003, 03:46 AM
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.
October 11th, 2003, 03:50 PM
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.