Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 926
Johnny Avatar asked Oct 13 '13 13:10

Johnny


People also ask

Can we initialize an array without size in C?

You can declare an array without a size specifier for the leftmost dimension in multiples cases: as a global variable with extern class storage (the array is defined elsewhere), as a function parameter: int main(int argc, char *argv[]) .

How do you declare an array of unknown size?

Technically, it's impossible to create an array of unknown size. In reality, it's possible to create an array, and resize it when necessary. Just use a string. Manipulate something like this to possibly fit in how you want it.

What happens if you don't initialize the size of an array?

Even if you do not initialize the array, the Java compiler will not give any error. Normally, when the array is not initialized, the compiler assigns default values to each element of the array according to the data type of the element.

Can arrays be initialized to zero size?

1. Initializing an array without assigning values: An array can be initialized to a particular size. In this case, the default value of each element is 0.


2 Answers

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];
like image 152
john Avatar answered Oct 18 '22 04:10

john


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.

like image 43
haccks Avatar answered Oct 18 '22 03:10

haccks