Is it possible to use malloc() to allocate an array at run time?
I tried the following and it just plain doesnt work:
var my_array_size = 100; var** my_array;
function my_function_startup() { var count; // allocate the array my_array = (var**)malloc(sizeof(var)*my_array_size); // initialize all array indexs to 0. count = 0; while(count<my_array_size) { my_array[count] = 0; count += 1; } }
I get a compile error on 'my_array[count] = 0;' - 'subscript requires an array or pointer type' - in other words, my_array isnt being allocated i think?
ive also tried 'my_array = (var**)malloc(sizeof(var*)*my_array_size);' and that doesnt do me any good either.
Re: using Malloc() to allotcate an array?
[Re: Caermundh]
#318865 04/10/1013:3004/10/1013:30
hummm, when I do the var* as a global it DOES work....bugger.
Heres what im actually doing: (I didnt post this because I didnt think it made a difference. Im still allocating to a var* either way, but obviously there is a difference if one way produces a compile error and the other doesn't)
<objects.h file> typedef struct my_struct { STRING* str1; var var1; var var2; var* my_array; struct my_struct* next; } my_struct;
struct_ptr = (my_struct*)malloc(sizeof(my_struct)); - I still get the error message this way
struct_ptr = (my_struct)malloc(sizeof(my_struct)); - gives me compile time error 'cannot convert pointer to struct my_struct'
struct_ptr = (my_struct*)malloc(sizeof(my_struct*)); - this line works fine, it lets me assign a string to str1 by struct_ptr->str1 = str_create("hello world") and lets me assign numbers to var1 & var2 by struct_ptr->var1 = 1;, etc.
Im allocating space for the structure, but I cant seem to allocate an array for struct_ptr->my_array.