C++:storing constant multi dimensional arrays in a pointer - c++

I'm working on a project of which I should store constant multi dimensional arrays.I would like to do it with a pointer which points to multi-dimensional arrays.However, I could'nt succeeded.I write this code but it didn't compiled.
int darray[1][2];
int darray2[2][3];
int (*p)[1][2];
p= new int[2];
p[0] = darray;
p[1] = darray2;

Well, let's go through your code line by line (OK, I'll lump the first two lines together)
int darray[1][2];
int darray2[2][3];
OK, this defines two two-dimensional arrays in exactly the way you (probably) expect. Note that formally, those are actually arrays of arrays of ints. More exactly, darray is of type "array of 1 array of 2 ints each", and darray2 is of type "array of 2 arrays of 3 ints each"
int (*p)[1][2];
This defines a pointer to a two-dimensional array of int, or to the first element of an array of such arrays. That is, the type of p is "pointer to array of 1 array of 2 ints each".
p= new int[2];
Here you are allocating space for two ints (i.e. an one-dimensional array of ints, of length two), and new returns a pointer to the first element of that array, i.e. a pointer to int. You try to assign that pointer to int to p, which is a pointer to array of 1 array of 2 ints each, as mentioned above. This gives a type mismatch and should not compile.
It's not entirely clear what you want at that point, but given that you do assignments to p[0] and p[1] afterward, and given that the return value is assigned to p which is of type int (*)[1][2] the obvious choice would be p = new int[2][1][2];
p[0] = darray;
This again doesn't work, because arrays in C++ are not first-class objects. That is, instead of assigning the value of darray to p[0] as the line would suggest (and p[0] indeed would have the right type for that) the rules of C++ say that the array darray is promoted to a pointer to its first element. That is, what this code actually tries to do is to assign a pointer to the first element of darray (of type int (*)[2]) to p[0] (of type int[1][2]), which of course fails. In C++, arrays are simply not assignable.
p[1] = darray2;
This suffers from the same problem, however note that even if arrays were first-class, assignable objects in C++, this still would be a type mismatch because p[1] is of type int[1][2] while darray2 is of type int[2][3].
Note that you get around most of those limitations (apart from the last one) by just wrapping you array into a class C++11 actually provides a standard class template called std::array for this purpose):
struct array12 { int data[1][2]; };
array12 darray;
array12* p;
p = new array12[2];
p[0] = darray;
With a bit more of programming you could also handle the assignment from larger to smaller arrays (your darray2 case) by copying only part of the data by hand.

Related

If `new int` returns an `int*`, then why doesn't `new int[n]` return an `int**`?

I am puzzled how both new int and new int[n] return an int*. Why doesn't the latter return an int**?
Here is some context: refer to the variable data below in a snippet from Goodrich, Tamassia, and Mount's 2nd ed. Data Structures and Algs in C++ textbook:
class Vect {
public:
Vect(int n);
~Vect();
// ... other public members omitted
private:
int* data;
int size;
};
Vect::Vect(int n) {
size = n;
data = new int[n];
}
Vect::~Vect() {
delete [] data;
}
(answers contains simplifications for the sake of explanations)
In C, a pointer to an array of ints would be of type int**, if I am not mistaken.
You are mistaken. In C it also would be int*, more precisely: int (*)[]
When you declare: int foo[] = { 1, 2, 3 }, the name of array (foo) can be in many cases effectively treated as pointer to its first element (1). The pointer to int is int*.
Additionally, why are we calling delete[] instead of delete, to delete an int* (data)?
delete deletes single object. delete [] removes dynamic array.
new int[n] cannot return a result of type int** because an int** value has to point to an object of type int* (a pointer object).
new int[n] allocates memory for an array of n objects, each of which is of type int. It does not create a pointer object.
The int* value it returns points to the initial (0th) element of the allocated array. Other elements of the array can be accessed by pointer arithmetic.
It could have been defined to yield a result of type int (*)[n], which is a pointer to an array of n int elements, except that (a) C++ doesn't permit arrays with non-constant bounds, and (b) even for something like int (*)[4], it's less convenient that int*.
C++, like its ancestor language C, treats arrays as second-class citizens. Array expressions, in most but not all contexts, are "converted" (adjusted at compile time) to pointer expressions, pointing to the initial element of the array object, and array elements are accessed using pointer arithmetic. (The indexing operator a[i] is syntactic sugar for *(a+i)).
Yes, it can all be confusing and counterintuitive.
Recommended reading: Section 6 of the comp.lang.c FAQ (most of it applies to both C and C++).

What are the exact differences betwenn int **a and int a[][] as function parameters in C and C++?

I have encountered this while writing a program with matrices, I used int** m to declare my matrix - because I needed dynamic allocation and in the function i used int a[][]. I don't remember having any problem with that. But when I used a simple m[6][6] matrix and f(int**m, int** m2, rest params) I had trouble.
It compiled and when I was running the program (code blocks with GCC) it just crashed. I tried debugging by adding printf()s and it was crashing at an if() block where it made no sense to crash. Modified the first function parameter from int a[][] to int* a[6] and it moved on, modified the second param later and my program worked on first try. By a more careful debug what I was saving in int m[i][j] and checking in the if was junk value, not what I was putting in, I was just putting 1 or 0 to mark something.
After all this years, unless I get compiler error by GCC when I do stuff like this, I just write the first way that comes to mind.
What is the logic behind using int** and int [][] to declare variable/get function parameters, in all 4 combinations? Most predefined functions I worked with use int** in the function header.
I know int [][] is not equivalent to int**, it is int* [] correctly, but what are the things that i'm missing? int[][] is an multi dimensional array means array of arrays, all 3 ways of writing it seem the same. And for int[][] it almost always asks to only let the first parameter void, like for int array[][][][] I need to put int array a[][n1][n2][n3] in the function parameter, right? It needs to know the dimension for multi-dimensional arrays except for the first one, because int* and int[] can be used without problems when declaring function arguments?
What are the exact differences betwenn int **a and int a[][] as function parameters in C and C++?
int *a. This is a pointer to an int.
int **a. This is a pointer to pointer to an int.
int a[] This would be an array of unspecified number of ints in all other contexts, but as a function parameter declarator, it is adjusted to be a pointer to int i.e. in that case it is same as if you had written int *a.
int a[][] This would be an array of unspecified number of arrays of unspecified number of ints, but such type is ill-formed because the array element cannot be an array of unspecified size.
int *a[] This would be an array of unspecified number of pointers to int in all other contexts, but as a function parameter declarator, it is adjusted to be a pointer to pointer to int i.e. in that case it is same as if you had written int **a.
int (*a)[N] This is a pointer to an array of N ints.
int a[][N] This would be an array of unspecified number of arrays of N ints in all other contexts, but as a function parameter declarator, it is adjusted to be a pointer to an array of N int i.e. in that case it is same as if you had written int (*a)[N].
Some examples:
void fun_1D(int*); // argument is pointer to int
void fun_1D(int[]); // same as above
void fun_1D(int[10]); // same as above; note that 10 is ignored
int arr_1D[20]; // array of int
fun_1D(arr_1D); // implicit conversion
fun_1D(&arr_1D[0]); // same as above
void fun_2D(int (*)[20]); // note that 20 is not ignored
void fun_2D(int[][20]); // same as above
void fun_2D(int[10][20]); // same as above; note that 10 is ignored
int arr_2D[20][20]; // array of array of int
fun_2D(arr_2D); // implicit conversion
fun_2D(&arr_2D[0]); // same as above
fun_1D(arr_2D[i]); // implicit conversion
fun_1D(&arr_2D[i][0]); // same as above
void fun_ptrs(int**); // argument is pointer to pointer to int
void fun_ptrs(int*[]); // same as above
void fun_ptrs(int*[10]); // same as above; note that 10 is ignored
int *arr_ptr[20]; // array of pointers
fun_ptrs(arr_ptr); // implicit conversion
fun_ptrs(&arr_ptr[0]); // same as above
fun_1D(arr_ptr[i]); // no conversion needed
// broken examples
fun_2D(arr_ptr); // int*[20] is not int(*)[20]
fun_ptrs(arr_2D); // int[20][20] is not int**
Notice how a function parameter declared as an array is adjusted as the same pointer type to which an array will decay to upon lvalue to rvalue conversion.
Some simple rules of thumb to remember:
An array is not a pointer.
A pointer is not an array.
A function argument written as an array is actually not an array. It is actually adjusted to be a pointer to the element of such array. After this adjustement, a function argument is never an array. This does not apply to any other contexts, except for function arguments.
Not every type can be element of an array. Arrays of unspecified length are such types.
There are no objects of "array unspecified length" types. They can only be used in extern variable declarations which refer to an array defined elsewhere, or in a definition where the actual size is deduced from the initialiser of the array, or in a function parameter declaration where the array is adjusted to be a pointer to the element.
If I declare int a[6][6] in main and call a function that expects int** a, will it workd?
No, because int[6][6] is not an int** and neither does it decay to one. int[6][6] decays to int(*)[6] as I explained above. int(*)[6] and int** are not convertible to one another. One is pointer to an array, the other is pointer to a pointer.
And the other way around
No, because int[6][6] argument is adjusted to int(*)[6]. See previous paragraph for reason why these are incompatible.
seems int a[][] is not accepted
Correct. As I explained in the fourth paragraph from the top (not counting the quote).
If I have functions f1(int *a) and f2(int a[]) and f2(int a[6]) what would sizeof (a) return in those cases ?
As I explained above, all of those declare a parameter of type int*. sizeof a would be same as sizeof(int*) because that is the type.
int **a
This is pointer to pointer to int.
int a[][]
This is array of array of int but this is not valid because the dimension of the second array must be known at declaration time, i.e. the second array must be complete, as it cannot be completed afterwards, like that
int a[][DIM]
C++ inherited C's behavior of arrays decaying into a pointer.
This behavior is really helpful, until one hits a sharp edge and realizes something odd is going on, and then one tries to figure out what it does and test out the behavior and realize it is a bit crazy.
But keep calm, once you realize what it means for an array to decay into a pointer, everything makes sense again.
Here is an example to illustrate the differences.
static void func1(int** p) {
(void)p;
}
static void func2(int (&a)[2][2]) {
(void)a;
}
int main() {
// x is a 2-dimensional array of int objects.
int x[2][2] = {{10, 20}, {30, 40}};
// x[0][0] is 10, and is at 0x1000 (say, for example)
// x[0][1] is 20, and is at 0x1004
// x[1][0] is 30, and is at 0x1008
// x[1][1] is 40, and is at 0x100C
// y is a 1-dimensional array of pointers.
int* y[2] = { &x[0][0], &x[1][0] };
// y[0] is 0x1000, and is at 0x1010 (say, for example)
// y[1] is 0x1008, and is at 0x1018
// x cannot decay into an int**, because it is not an array of pointers.
// y can decay into an int**, because it is an array of pointers.
func1(y);
// x can be used for an int[2][2] reference parameter.
// y cannot be used for an int[2][2] reference parameter.
func2(x);
}
When you declare arrays in C++ you are allocating a contigious block of memory that holds the members of the array.
int data[6]; // Block of 6 integers.
This is true even for dimensional arrays.
int threeD[2][3][4]; // Allocates a Block of 24 integers.
// The compiler keeps track of the number of
// of dimensions and does the maths for you
// to calculate the correct offset.
Now when an array is passed to a function the array will decay into a pointer to the first element.
Now if you are dynamically allocating a multi-dimensional array. You tend to do this as arrays of arrays. These arrays are NOT in contiguous memory. But you need to do it this way to allow you to use the square bracket operator [] as you would do normally.
int*** dynamicThreeD = new int**[2];
for(int l1 = 0 ; l1 < 2 ; ++l1) {
dynamicThreeD[l1] = new int*[3];
for(int l2 = 0 ; l2 < 3 ; ++l2) {
dynamicThreeD[l1][l2] = new int[4];
}
}
int threedD[2][3][4];
Though these two types look the same in the way they are accessed:
dynamicThreeD[1][2][3] = 8;
threeD[1][2][3] = 8;
These are not the same. The dynamicThreeD at ache [] is accessing the array and retrieving the next pointer for referencing next. While the threeD object results in an index calculation (3) + (4 * 2) + (4*3 * 1) which is then used as an offset from the first element.
dynamicThreeD[1][2][3] = 8;
// Equivalent to
int** tmp1 = dynamicThreeD[1];
int* tmp2 = tmp1[2];
tmp2[3] = 8;
threeD[1][2][3] = 8;
// Equivalent to
int index = (3) + (4 * 2) + (4*3 * 1)
// OK The compiler does not take the address like this
// But I needed to do some type gymnastics to convert the type
// at the language level.
//
// But you get the same effect like this.
// As the value is just offset by an index from the beginning of
// the array.
(&threed[0][0][0])[index] = 8;
The side affect of this is that multi dimensional arrays can be much more efficient as 1) we only need to do one memory accesses (not 3) get/set the data. 2) Because of data locality and caching you get a much better hit ratio.
On the other hand multi-dimensional arrays in parallel systems can be a pain if you have multiple writers as cache consistency becomes an issue if all the members are all in the same cache line. Here the array of array has an advantage as each line can be in a distinct part of memory and worked on independently (Note: I am oversimplify a very complex issue).
Among the other well answers, I want to focus your last concern.
"And for int[][] it almost always asks to only let the first parameter void, like for int array[][][][] I need to put int array a[][n1][n2][n3] in the function parameter, right?"
Yes, only the first dimension can be left unspecified. But if you want to have the other dimensions to be variable/determined at runtime, at least in C you can use:
int foo (int n1, int n2, int a[][n1][n2]) { ...
With an additional level of indirection, you can pass a fixed size of dimensions, since sizeof(*x), sizeof(x[0][0]) etc. knows the dimensions of the indirect type.
But generally in C, the array [] is just a pointer * and the size, especially when dynamic, needs to be passed or known, as a second parameter, global, MACRO, or in a struct, until classes come along. Of course, there is the null term thing used so much with char* and char**argv. For pointers, you pay 8 bytes overhead.

What is the method to reassign a data point in an int array within c++ using pointers

for my class I have to demonstrate manipulating an array with pointers. The first part was to output a value using pointers which I have already done. The second part is the one I need help with. With the given code, I must output ar[0][3] using the pointer p. I am not asking for an answer, I just want to know how this is to be done. Also, I don't know why pointer p and q both initialize to the address of 9 when I start the program. That's just a side question. Here is the given code.
int ar[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12};
int **p;
int *q;
p=&q;
q =*(ar+2);
Write using pointer arithmetic how would change the value of ar[0][3] using pointer p.
I will also email my teacher to ask but it is unlikely he will respond today, that is why I am asking you guys. Thanks in advance.
how would change the value of ar[0][3] using pointer p.
First, assign q to point to ar[0][3]. It is unclear whether the arbitrary requirement to use p applies to this, but let's assume that q must be modified by indirecting through p:
*p = &ar[0][3];
Then indirect through q to access the element, and change the value by assigning it:
**p = new_value;
is there a reason I cannot simply use *p = new_value?
p is a pointer to a pointer to integer. When you indirect through p, you get the pointer to integer that is being pointed at. You cannot assign an integer value to a "pointer to integer". You have to indirect through the "pointer to integer" to get access to pointed integer. So, first indirect through the pointer to pointer to integer in order to get the pointer to integer, then indirect through the pointer to integer in order to get the integer, whose value you can assign. I.e. **p = new_value;
or will [*p = new_value] simply overwrite *p?
Yes. Assigning to an object overwrites the value of the object. In this case, the assigned object is the pointer q.
I find it's easier to reason about arrays if you don't try to think of a 2D array as something special. It isn't. It's just an array of arrays.
int **p is not the right type to use. An array of arrays of int cannot be converted into a pointer to a pointer to an int.
An array can decay into a pointer to its first element. So what's the type of the first element of an array of 3 arrays of 4 ints? It's an array of 4 ints. That means that the type that an int[3][4] will decay into isn't int**, it's int (*)[4]: a pointer to an array of 4 ints.
int ar[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
// ar decays to a pointer to its first element, which is an array of 4 ints,
// so p is a pointer to an array of 4 ints, pointing to the first element of ar
int (*p)[4] = ar;
// You can then dereference p, yielding an array of 4 ints.
// That array decays to a pointer to its first element, which is an int,
// so q is a pointer to an int, pointing to the first element of the first element
// of ar
int *q = *p;
// To get the 3rd element of the first element of ar, shift q 2 positions and then
// dereference the resulting pointer
std::cout << *(q + 2); // output the desired element
Live Demo
Of course, you don't need the intermediate variables p and q. You could just do everything in one line:
int ar[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
// 1. ar decays to a pointer to its first element
// 2. Dereference the pointer that ar decayed into
// 3. The array yielded by the dereference in (2) decays into a pointer to
// its first element
// 4. Offset the pointer that results from (3) by two positions
// 5. Dereference the pointer from (4) to access the third element of the
// first element of ar
std::cout << *(*ar + 2);
Live Demo
This is a pretty complex single line though, so the extra intermediate variables can help make it more clear what's going on.
So you figured out how to manipulate a 1-Dimensional array with pointers. This is easy since an array can be simply treated as a pointer and the number inside the square brackets is just a way to increment the pointer arr[i] is equivalent to *(arr+i). Similar approach can be done for a 2-Dimensional array, for an array arr[i][j], we first de-refrence arr+i to get a new array containing the j members, then we de-reference *(arr+i)+j to get finally ((arr+i)+j), the code should look something like this:
#include <iostream>
using namespace std;
int main()
{
int arr[3][3] = {1,2,3,
4,5,6,
7,8,9};
int i=1,j=2;
cout << *(*(arr+i)+j);
}
So another example, if we have an 3-dimensional array, arr[a][b][c], to extract an element using pointers we may do it like this:
*(*(*(arr+a)+b)+c)

difference between pointer to an array and pointer to the first element of an array

int (*arr)[5] means arr is a pointer-to-an-array of 5 integers. Now what exactly is this pointer?
Is it the same if I declare int arr[5] where arr is the pointer to the first element?
Is arr from both the examples are the same? If not, then what exactly is a pointer-to-an-array?
Theory
First off some theory (you can skip to the "Answers" section but I suggest you to read this as well):
int arr[5]
this is an array and "arr" is not the pointer to the first element of the array. Under specific circumstances (i.e. passing them as lvalues to a function) they decay into pointers: you lose the ability of calling sizeof on them.
Under normal circumstances an array is an array and a pointer is a pointer and they're two totally different things.
When dealing with a decayed pointer and the pointer to the array you wrote, they behave exactly the same but there's a caveat: an array of type T can decay into a pointer of type T, but only once (or one level-deep). The newly created decayed type cannot further decay into anything else.
This means that a bidimensional array like
int array1[2][2] = {{0, 1}, {2, 3}};
can't be passed to
void function1(int **a);
because it would imply a two-levels decaying and that's not allowed (you lose how elements of the array are laid out). The followings would instead work:
void function1(int a[][2]);
void function1(int a[2][2]);
In the case of a 1-dimensional array passed as lvalue to a function you can have it decayed into a simple pointer and in that case you can use it as you would with any other pointer.
Answers
Answering your questions:
int (*arr)[5]
this is a pointer to an array and you can think of the "being an array of 5 integers" as being its type, i.e. you can't use it to point to an array of 3 integers.
int arr[5]
this is an array and will always behave as an array except when you pass it as an lvalue
int* ptrToArr = arr;
in that case the array decays (with all the exceptions above I cited) and you get a pointer and you can use it as you want.
And: no, they're not equal otherwise something like this would be allowed
int (*arr)[5]
int* ptrToArr = arr; // NOT ALLOWED
Error cannot convert ‘int (*)[5]’ to ‘int*’ in initialization
they're both pointers but the difference is in their type.
At runtime, a pointer is a "just a pointer" regardless of what it points to, the difference is a semantic one; pointer-to-array conveys a different meaning (to the compiler) compared with pointer-to-element
When dealing with a pointer-to-array, you are pointing to an array of a specified size - and the compiler will ensure that you can only point-to an array of that size.
i.e. this code will compile
int theArray[5];
int (*ptrToArray)[5];
ptrToArray = &theArray; // OK
but this will break:
int anotherArray[10];
int (*ptrToArray)[5];
ptrToArray = &anotherArray; // ERROR!
When dealing with a pointer-to-element, you may point to any object in memory with a matching type. (It doesn't necessarily even need to be in an array; the compiler will not make any assumptions or restrict you in any way)
i.e.
int theArray[5];
int* ptrToElement = &theArray[0]; // OK - Pointer-to element 0
and..
int anotherArray[10];
int* ptrToElement = &anotherArray[0]; // Also OK!
In summary, the data type int* does not imply any knowledge of an array, however the data type int (*)[5] implies an array, which must contain exactly 5 elements.
A pointer to an array is a pointer to an array of a certain type. The type includes the type of the elements, as well as the size. You cannot assign an array of a different type to it:
int (*arr)[5];
int a[5];
arr = &a; // OK
int b[42];
arr = &b; // ERROR: b is not of type int[5].
A pointer to the first element of an array can point to the beginning of any array with the right type of element (in fact, it can point to any element in the array):
int* arr;
int a[5];
arr = &a[0]; // OK
int b[42];
arr = &b[0]; // OK
arr = &b[9]; // OK
Note that in C and C++, arrays decay to pointers to the type of their elements in certain contexts. This is why it is possible to do this:
int* arr;
int a[5];
arr = a; // OK, a decays to int*, points to &a[0]
Here, the type of arr (int*) is not the same as that of a (int[5]), but a decays to an int* pointing to its first element, making the assignment legal.
Pointer to array and pointer to first element of array both are different. In case of int (*arr)[5], arr is pointer to chunk of memory of 5 int. Dereferencing arr will give the entire row. In case of int arr[5], arr decays to pointer to first element. Dereferencing arr will give the first element.
In both cases starting address is same but both the pointers are of different type.
Is it the same if i declare int arr[5] where arr is the pointer to the first element? is arr from both example are same? if not, then what exactly is a pointer to an array?
No. To understand this see the diagram for the function1:
void f(void) {
int matrix[4][2] = { {0,1}, {2,3}, {4,5}, {6,7} };
char s[] = "abc";
int i = 123;
int *p1 = &matrix[0][0];
int (*p2)[2] = &matrix[0];
int (*p3)[4][2] = &matrix;
/* code goes here */
}
All three pointers certainly allow you to locate the 0 in matrix[0][0], and if you convert these pointers to ‘byte addresses’ and print them out with a %p directive in printf(), all three are quite likely to produce the same output (on a typical modern computer). But the int * pointer, p1, points only to a single int, as circled in black. The red pointer, p2, whose type is int (*)[2], points to two ints, and the blue pointer -- the one that points to the entire matrix -- really does point to the entire matrix.
These differences affect the results of both pointer arithmetic and the unary * (indirection) operator. Since p1 points to a single int, p1 + 1 moves forward by a single int. The black circle1 is only as big as one int, and *(p1 + 1) is just the next int, whose value is 1. Likewise, sizeof *p1 is just sizeof(int) (probably 4).
Since p2 points to an entire ‘array 2 of int’, however, p2 + 1 will move forward by one such array. The result would be a pointer pointing to a red circle going around the {2,3} pair. Since the result of an indirection operator is an object, *(p2 + 1) is that entire array object, which may fall under The Rule. If it does fall under The Rule, the object will become instead a pointer to its first element, i.e., the int currently holding 2. If it does not fall under The Rule -- for instance, in sizeof *(p2 + 1), which puts the object in object context -- it will remain the entire array object. This means that sizeof *(p2 + 1) (and sizeof *p2 as well, of course) is sizeof(int[2]) (probably 8).
1 Above content has been taken from More Words about Arrays and Pointers.
The address of the whole array, and the address of the first element, are defined to be the same, since arrays in C++ (and C) have no intrinsic padding besides that of the constituent objects.
However, the types of these pointers are different. Until you perform some kind of typecast, comparing an int * to an int (*)[5] is apples to oranges.
If you declare arr[5], then arr is not a pointer to the first element. It is the array object. You can observe this as sizeof( arr ) will be equal to 5 * sizeof (int). An array object implicitly converts to a pointer to its first element.
A pointer to an array does not implicitly convert to anything, which may be the other cause of your confusion.
If you write int arr[5], you are creating an array of five int on the stack. This takes up size equal to the size of five ints.
If you write int (*arr)[5], you are creating a pointer to an array of five int on the stack. This takes up size equal to the size of a pointer.
If it is not clear from the above, the pointer has separate storage from the array, and can point at anything, but the array name cannot be assigned to point at something else.
See my answer here for more details.

ELI5: What is the data type of `int *p[]`

I don't understand what the datatype of this is. If its a pointer or an array. Please explain in simple terms. To quote what was in the book-
If you want to pass an array of pointers into a function, you can use the same method that you use to pass other arrays—simply call the function with the array name without any indexes. For example, a function that can receive array x looks like this:
void display_array(int *q[])
{
int t;
for(t=0; t<10; t++)
printf("%d ", *q[t]);
}
Remember, q is not a pointer to integers, but rather a pointer to an array of pointers to
integers. Therefore you need to declare the parameter q as an array of integer pointers,
as just shown. You cannot declare q simply as an integer pointer because that is not
what it is.
cite: C++: The Complete Reference, 4th Edition by Herbert Schildt, Page 122-123
This is how it's built up:
int is the type "int".
int* is the type "pointer to int"
int* [] is the type "array (of unknown bound/length) of pointer to int"
int* p[] is the declaration of a variable or parameter named p of the type above.
... pointer to an array of pointers to integers
No it's not. q is the type int *[]. Which is an invalid (or possibly incomplete, depending on context) type in C++, and only valid in some places in C. Arrays must have a size.
The type int *[] is an (unsized) array of pointers to int. It is itself not a pointer.
The confusion probably comes from the fact that an array can decay to a pointer to its first element.
For example, lets say we have this array:
int a[20];
When plain a is used, it decays to a pointer to its first element: a is equal to &a[0].
int *p[]
// ^
p is
int *p[]
// ^^
p is an array of unspecified size (possibly illegal, depends on context)
int *p[]
// ^^^^^
p is an array of unspecified size of pointers to int
Meaning each element of p is a pointer:
int foobar = 42;
p[0] = NULL;
p[1] = &foobar;
I don't understand what the datatype of this is
If it's any comfort, neither does the author of the book you are reading.
Remember, q is not a pointer to integers, but rather a pointer to an array of pointers to integers.
This is bullschildt.
Before adjustment of parameters, q is an array of pointers to integers.
After adjustment of parameters, q is a pointer to the first element of an array of pointers to integers. Equivalent to int** q, a pointer to pointer to an int.
Nowhere is it "a pointer to an array of pointers to integers". That would have been int* (*q)[].
I would advise to stop reading that book.
The key here is that any array that is part of a parameter list of a function, gets adjusted ("decays") into a pointer to the first element. So it doesn't matter if you type int* q[666] or int* q[], either will be silently replaced by the compiler with int** "behind the lines".
This is actually the reason why we can write [] in a parameter list - normally an empty array would be an incomplete type that can't be used before completion elsewhere. But since parameters always get adjusted, they are never of array type, and it doesn't matter that the original type was incomplete.