Pointer to array...?

http://ideone.com/FrolQl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <typeinfo>

int main()
{
	using Arr_t = int[7];
	auto arr = new Arr_t;
	std::cout << typeid(Arr_t).name() << std::endl;
	std::cout << typeid(arr).name() << std::endl;
	std::cout << typeid(*arr).name() << std::endl;
	std::cout << typeid(arr[0]).name() << std::endl;
	std::cout << typeid(new Arr_t).name() << std::endl;
	std::cout << typeid(new Arr_t[4]).name() << std::endl;
	delete arr;
}







A7_i
Pi
i
i
Pi
PA7_i
I'm having trouble understanding the last output - what's going on here?
Last edited on
$ ./test | c++filt -t
int [7]
int*
int
int
int*
int (*) [7]


The only thing I see that may not be obvious is that when you use new to create an object of array type, you get a pointer to the first element of that array (and you're under the obligation to use delete[] on that pointer)

The last new is asked to build an array of 4 arrays of 7 ints, so it returns a pointer to the first element (that is a pointer to the first array of 7 ints)
Last edited on
Wow, this is actually really confusing to me. So line 14 should be delete[] arr;? I'm also still confused about the 4-element array of 7-element arrays - how does that work?
Last edited on
yes, line 14 should be delete[] arr;, right now valgrind tells me

==10648== Mismatched free() / delete / delete []
==10648==    at 0x4A06E4E: operator delete(void*) (vg_replace_malloc.c:480)
==10648==    by 0x400BC5: main (test.cc:14)
==10648==  Address 0x4c38040 is 0 bytes inside a block of size 28 alloc'd
==10648==    at 0x4A07FE8: operator new[](unsigned long) (vg_replace_malloc.c:363)
==10648==    by 0x400ADD: main (test.cc:7)


an array of 4 arrays of 7 elements is just int[4][7]. even without any new,
int arr[4][7];
int (*p)[7] = arr; // or = &arr[0] if you like
Ah, ok. I guess the idea of dynamically allocating it was throwing me off.
1
2
3
4
5
	new int[1][2][3]; //I thought this would be an error
	new int[x][2][3]; //I thought this would be an error
//	new int[1][x][3]; //this is an error
//	new int[1][2][x]; //this is an error
//	new int[x][x][x]; //this is an error 
Topic archived. No new replies allowed.