How to declare sysconf return value in global array declaration?

I wrote a program to save all the detailed file descriptors.

So, I used the sysconf function to resolve the open max file descriptor.

if the array declaration is not in the global value, it does not indicate an error. Works fine.

This is my program

#define MAX_CLIENT sysconf(_SC_OPEN_MAX) int arr[MAX_CLIENT]; main () { printf("%ld \n",MAX_CLIENT); } 

when i do compilation with error message

 error: variably modified 'arr' at file scope 

Then I checked with the cc -E option. After the preprocessor works, the programs look as follows:

 int arr[sysconf(_SC_OPEN_MAX)]; main () { printf("%ld \n",sysconf(_SC_OPEN_MAX)); } 

this is my problem how to declare an array globally.

+4
source share
2 answers

The easiest option is to dynamically allocate the array using malloc() :

 int *arr; int main(void) { arr = malloc(sysconf(_SC_OPEN_MAX) * sizeof(int)); ... free(arr); } 

The code that you have now will work, but only if arr was declared inside the function. He will then use the C99 function, called variable-length arrays .

+3
source

You cannot determine a global array by size that is unknown at compile time.

The simplest solution is to define a global pointer and assign it to the memory allocated at the beginning of main .

0
source

Source: https://habr.com/ru/post/1393752/


All Articles