I want to declare an two dimension array, but I don't know first dimension. Second dimension is known.
How do I declare the array?
I found one syntax:
int (*p) [5];
Is it correct syntax? But I do not understand this syntax.
I want to declare an two dimension array, but I don't know first dimension. Second dimension is known.
How do I declare the array?
I found one syntax:
int (*p) [5];
Is it correct syntax? But I do not understand this syntax.
You have to use dynamic memory ;)...
#include <stdlib.h>
#include <stdio.h>
#define KNOWN_DIMENSION 16
int main() {
size_t unknownDimension = rand() % 32 + 1;
int **dynamic = malloc(unknownDimension * sizeof(int*));
if(dynamic == NULL) {
fprintf(stderr, "Unable to allocate\n");
return -1;
}
for(size_t i = 0; i < unknownDimension; i++) {
dynamic[i] = malloc(KNOWN_DIMENSION * sizeof(int));
if(dynamic[i] == NULL) {
fprintf(stderr, "Unable to allocate\n");
return -1;
}
}
// `dynamic` is usable as an `int[unknownDimension][KNOWN_DIMENSION]` here!
for(size_t i = 0; i < unknownDimension; i++)
free(dynamic[i]);
free(dynamic);
return 0;
}
BTW: int (*p)[5]
is the same as a pointer to int p[5]
.
int (*p) [5];
means "p is a pointer to an array of five ints".
This pointer can be a pointer to the first element of an array in the normal way.
If you have an array whose elements are five-element arrays of int
s, you can use the normal array-to-pointer conversion:
int array[10][5] = {};
int (*p)[5] = array;
or
int (*p)[5] = &array[0];
You can of course also allocate dynamically, which I suspect you want to do:
int (*p)[5] = new int[10][5];
Unfortunately this requires dynamic memory.
However if standard containers can be used C++11 provides the array
container:
vector<array<int, 5>> foo;
Which provides 4 primary benefits over dynamic memory:
foo
: For example to create two size 5, zeroed second dimensions you need only do: foo.resize(2)
delete
allocated memory. As soon as foo
goes out of scope it will be cleaned up. Whether by throwing an error or any natural scope exitvector
can attend to reallocation and data copying as the array dynamically grows or shrinks over the course of program execution