Defining a global structure pointer in C?

I need to define a global structure (array) consisting of 4 integers. The problem is that the size of this array is not known in advance.

I am trying to do sth. eg:

typedef struct { int value; int MAXleft; int MAXright; int MAX; } strnum; int main () { int size; scanf("%d", &size); strnum numbers[size]; return 0; } 

I heard that this can be done with pointers, but I do not know how to do it.

+4
source share
3 answers

You can allocate space for several structures dynamically as follows:

 strnum *numbers = malloc( size * sizeof(strnum) ); 

Then you can use it like any regular array (basically).

It may be more convenient to use calloc instead of malloc . It selects several blocks and fills them with zeros. Note that malloc does not clear allocated memory.

 strnum *numbers = calloc( size, sizeof(strnum) ); 

When you finish working with memory, do not forget to call free( numbers ) , which will return the allocated memory back to the memory manager.

If you are not free , when it is no longer required and allocates more and more, the amount of memory in the program will grow without a good reason, as the program continues to work. This is called a memory leak and should be avoided. This can ultimately lead to a lack of memory for the program and unpredictable results.

And don't forget to include the stdlib.h header with prototypes of memory allocation functions.

+5
source

It is called Dynamic Memory Allocation.

What you are trying to do can be done as follows:

  strnum* number; int size = 0; scanf("%d",&size); number = malloc(size * sizeof(strnum)); 

Also, don't forget to free up memory after you have done this with an array.

  free(number); 
0
source

You can start with malloc () and then realloc () as the size continues to increase. I would suggest you allocate a pool of 10 structures at once to reduce the number of calls to realloc ().

0
source

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


All Articles