PDA

View Full Version : global arrays in C


somealien
06-13-02, 14:44
I'm trying to create an uninitialized global array in C ... does anyone know if i can do this, even? i want the user to enter the dimentions of the array in the main method so i can't just say float array[user_input]; because user_input is not yet given a value.

does anyone know how to do this (preferably without pointers)?

thanks a lot :)

Apel
06-18-02, 06:00
Well, arrays in c are not really much more than a pointer to the first element of it. There is no bounds checking at all. So using arrays is actually working with pointers. You can use malloc to allocate memory for a variable size array.


unsigned int array_size;
A_NICE_TYPE *myarray;

/*...*/

scanf("%u",&array_size);
myarray = malloc(sizeof(A_NICE_TYPE)*array_size);
if(myarray == NULL)
{
/*out of mem*/
}

/*have fun with your array*/

free(myarray);


You can access the array just like every normal array.
myarray[0] does the same as *myarray
and don't forget the free :)