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)?
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[]) .
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.
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.
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.
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With