help! i'm trying to declare a global array in C but don't know how to. i want it to be uninitialized and have the user input the dimention later (and THEN initialize it) ... is this possible? do i HAVE to use pointers? :-\
thanks.
help! i'm trying to declare a global array in C but don't know how to. i want it to be uninitialized and have the user input the dimention later (and THEN initialize it) ... is this possible? do i HAVE to use pointers? :-\
thanks.
>i'm trying to declare a global array in C but don't know how to.
Declare the array outside of any function. Then it is global to all functions in the file and can also be used by functions in other files.
>have the user input the dimention later
So you want a dynamically created array. Yes, then you will need pointers. Just declare a global variable like:
int *dynamic_array;
Which is a pointer to int. With malloc() you can allocate a block of ints. Like:
dynamic_array = malloc (sizeof (int) * array_size);
And don't forget to free the memory when you don't use the memory anymore or before exiting the program.
free (dynamic_array);
>do i HAVE to use pointers?
If the user is going to define the size of the array at run-time, then you must use pointers and dynamic memory allocation to simulate a dynamic array. As it is, you seem to want something like this:
-PreludeCode:#include <stdlib.h> int *globalArray; int main ( void ) { int size; puts ( "Enter the number of elements in the array" ); scanf ( "%d", &size ); globalArray = malloc ( size * sizeof *globalArray ); if ( globalArray != NULL ) { /* All is well, work with the new array */ free ( globalArray ); } else { /* malloc failed, try again or abort */ } return EXIT_SUCCESS; }
My best code is written with the delete key.