Reputation: 11
I have this in my main code , and It will give error because of too many data in initialization. I can't change int ** point phrase. how can initialize it?
int** points = { { 3, 6, 1, 4 }, { 17, 15, 1, 4 }, { 13, 15, 1, 4 }, { 6, 12, 1, 4 },
{ 9, 1 ,1,4}, { 2, 7,1,4 }, { 10, 19,1,4 } };
thank you in advance
Upvotes: 1
Views: 56
Reputation: 310930
It seems what you want is the following:)
int **points = new int *[7]
{
new int[4] { 3, 6, 1, 4 }, new int[4] { 17, 15, 1, 4 }, new int[4] { 13, 15, 1, 4 },
new int[4] { 6, 12, 1, 4 }, new int[4] { 9, 1, 1, 4 }, new int[4] { 2, 7, 1, 4 },
new int[4] { 10, 19, 1, 4 }
};
Take into account that you need explicitly to free all allocated memory when the arrays will not be needed any more.
For example
for ( size_t i = 0; i < 7; i++ ) delete [] points[i];
delete [] points;
You could also use a pointer declared like
int ( *points )[4];
In this case you could indeed allocate dynamically a two-dimensional array.
Upvotes: 1
Reputation: 726489
If you must keep points
a pointer to a pointer, you can initialize it like this:
// Construct the individual sub-arrays for the nested dimension
int pt0[] = { 3, 6, 1, 4 };
int pt1[] = { 17, 15, 1, 4 };
int pt2[] = { 13, 15, 1, 4 };
int pt3[] = { 6, 12, 1, 4 };
int pt4[] = { 9, 1, 1, 4 };
int pt5[] = { 2, 7, 1, 4 };
int pt6[] = { 10, 19, 1, 4 };
// Construct an array of pointers
int* pts[] = { pt0, pt1, pt2, pt3, pt4, pt5, pt6 };
// Convert an array of pointers to a double-pointer
int** points = pts;
This assumes static initialization context (e.g. global variables). If the context is not static, using points
must be confined to the scope of the inner arrays to which it points. For example, you cannot return points
from a function.
If you want to return a pointer from a function, you could use static
, like this:
static int pt0[] = { 3, 6, 1, 4 };
static int pt1[] = { 17, 15, 1, 4 };
...
static int* pts[] = { pt0, pt1, ... };
int** points = pts; // no "static" here
...
return points;
Note, however, that the function will be returning the same pointer every time that you call it.
Upvotes: 0