Initializing Arrays in C/C++ With Unknown Size [closed]

孤街浪徒 提交于 2020-06-10 15:11:17

问题


How can I initialize an array in C such as

void initArr(int size)
{
  ...
}

The C language does not give the option to initialize an array if his size is not an constant value, and if I initialize it generally (int *arr;) so it gives me error of 'arr' is not being initialized.

Similarily, how can I do that when I have an array with dimension bigger than one (matrix, for example)?


回答1:


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

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

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

int* arr = new int[size];



回答2:


The C language does not give the option to initialize an array if his size is not an constant value

In C99 you can use a variable length array and then initialize it by using a loop.

if I initialize it generally (int *arr;) so it gives me error of 'arr' is not being initialized.

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




回答3:


In C, you can initialize objects to 0 with memset. It's not possible to use memset to portably initialize objects other than character arrays to a repeated non-zero value.

In C++, the same is true, but it is restricted to so-called "POD" objects (Plain Old Data), which are basically the same objects you could have in C (no virtual functions, no private data members, etc. -- the precise definition is in the standard). It's not good C++ style, but it's possible.

In both C and C++ you can find the total size of an array in bytes (which you need to pass to memset) by multiplying the dimensions and the size of a single data element. For example:

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 so, you can use the sizeof operator directly on the array, which can be a lot more convenient. But there are lots of restrictions on VLAs; they often don't work the way you expect them to. However, the following does work:

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 may actually create run-time code, and therefore violates the expectation of many programmers that sizeof does not evaluate its argument.



来源:https://stackoverflow.com/questions/19345893/initializing-arrays-in-c-c-with-unknown-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!