4

I want to set a global reference of an int array, in C language, but I want to initialize it inside main function (actually the user is going to declare its size). Anyone knows how is this done?

Thanks in advance!

2
  • Using global variables is usually not a good solution, why don't you pass the array and its size to the function from the other modules? Commented Jan 17, 2016 at 1:10
  • 2
    Formally, you can't do that. The size of a global array is fixed at compilation time. You can achieve the equivalent effect by using a global pointer and allocating the correct space before any code uses it. But it is usually a good idea to avoid using global variables. It is not always a good idea: stdin, stdout and stderr are global variables, and it would be a confounded nuisance if they weren't. OTOH, errno is global and manages to present problems, though the standard has now partially neutralized the worst of them. Commented Jan 17, 2016 at 1:19

1 Answer 1

7

Declare a pointer to an int as a global variable and initialize it in main using malloc.

/* outside any function, so it's a global variable: */
int *array;
size_t array_size;

/* inside main(): */
array_size = user_defined_size;
array = malloc( sizeof(int)*array_size);
if ( array == NULL) {
    /* exit - memory allocation failed. */
}
/* do stuff with array */
free(array);

If you need to access the global variable from another module (source file), declare it there again using

extern int *array;
extern size_t array_size;

or, preferably, declare them extern in a header file included in any source file that uses the array, including the source where they are defined (to ensure type consistency).

Sign up to request clarification or add additional context in comments.

1 Comment

The header should be used in the file where the pointer (array) is defined as well as in the source files that use the array. That ensures (or does the most that can be done to ensure) that the definitions and uses of the array and its size are consistent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.