I hesitate to post this at all, but I hope it won't cause a problem.
To be pedantic: most of the other answers are wrong: what you've created is not a pointer to an array. It's a pointer to an int
that refers to the initial element of the array.
I hesitate to post about it for the simple reason that this is almost certainly just a matter of having used the wrong wording in your question -- a pointer to int
is almost certainly what you thought wanted, and it is what you really got.
There is, however, such as thing as a pointer to an array. It's rarely useful because when/if you do pointer math on it (including subscripting), a pointer to an array works in increments the size of the array it's pointing at. In your case you allocate 10 int
s. You can use subscripting off the pointer to refer to the int
s in the array, so theName[0]
refers to the first int
, theName[1]
to the second int
, and so on -- exactly what you usually want.
You might be able to make real use of a pointer to an array if you were working with (for example) an array of arrays, and wanted a pointer that would walk through that an entire row at a time, so ptr[0]
was the first row, ptr[1]
the second row, and so on. For example:
#include <iostream>
static const int x = 20;
static const int y = 10;
int main() {
char data[y][x];
auto ptr_array = &data[0];
char *ptr_char = &data[0][0];
std::cout << "Address of entire array: " << (void *)data << "\n";
std::cout << "char *[0] = " << (void *)ptr_char << "\n";
std::cout << "char *[1] = " << (void *)(ptr_char+1) << "\n";
std::cout << "array *[0] = " << (void *)ptr_array << "\n";
std::cout << "array *[1] = " << (void *)(ptr_array+1) << "\n";
return 0;
}
I've changed this to work with an array of arrays of char
(instead of int
) to make the math a little more apparent -- sizeof(char) == 1
(by definition) so it's a little easier to work out the math. When I run this code on my machine the addresses I get are:
Address of entire array: 0047FD2C
char *[0] = 0047FD2C
char *[1] = 0047FD2D
array *[0] = 0047FD2C
array *[1] = 0047FD40
As you can see, ptr[0]
holds the address of the array as a whole either way. However, with a pointer to char
, ptr[1]
holds an address one greater. The pointer to the array, however, holds an address 0x40 - 0x2C = 0x14 = 20 greater -- which fits with the X dimension we gave to the array (20). In other words, we really do have a pointer to an array, and pointer arithmetic (or, equivalently, subscripting) on this pointer works in terms of an entire array at a time.
I'll repeat though: at least if we ignore the fact that you almost certainly should be using an std::vector
instead, the type you wanted and the type you got were both pointer to int
. There such a type as pointer to array
, but it's almost certainly not want you really wanted.