Initializing Arrays in C / C ++ with Unknown Size

How can I initialize an array in C for example

void initArr(int size) { ... } 

The C language makes it impossible to initialize an array if its size is not a constant value, and if I initialize it at all (int * arr;), so this gives me the error 'arr' is not initialized.

Similarly, how can I do this when I have an array with a dimension greater than one (e.g. matrix)?

+6
source share
3 answers

The answer that works in C and C ++ is dynamic memory allocation

 int *arr = (int*)malloc(size*sizeof(int)); 

In C ++, you prefer to use new instead of malloc, but the principle is the same.

 int* arr = new int[size]; 
+10
source

C language makes it impossible to initialize an array if its size is not a constant value

In C99, you can use a variable-length array and then initialize it with a loop.

if I initialize it at all (int * arr;), so it gives me the error "arr", it does not initialize.

This is because the pointer must be initialized (pointing to pointee - excluding NULL) before it is used in the program.

+1
source

In C, you can initialize objects to 0 with memset . It is not possible to use memset for portability of initializing objects other than character arrays to a repeated non-zero value.

In C ++, the same is true, but it is limited to the so-called POD (Plain Old Data) objects, which are basically the same objects that you could have in C (no virtual functions, no private data elements, etc.) e. - the exact definition is in the standard). This is not a good C ++ style, but it is possible.

In C and C ++, you can find the total size of the array in bytes (which you need to pass to memset ) by multiplying the sizes and sizes of one data element. For instance:

 void InitializeMatrix(double *m, size_t rows, size_t cols) { memset(m, 0, rows * cols * sizeof *m); } 

In C99, you can declare a variable-length array (VLA) even with multiple dimensions, and if you do, you can use the sizeof operator directly in the array, which can be much more convenient. But there are many limitations to OLA; they often do not work as you expect. However, the following works:

 double m[rows][cols]; memset(m, 0, sizeof m); 

Note that in C99, unlike traditional C or C ++, the compiled sizeof operator in this case can actually create code at run time and, therefore, violates the expectations of many programmers who sizeof do not evaluate their argument.

0
source

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


All Articles