Why is this code giving me a segmentation fault?

I don't understand why the following code gives me a segfault. I thought this would make all the elements of the pointer-array point to dynamically allocated ints whose values are all 5.

1
2
3
4
5
6
7
8
9
10
11
12
int* ip_arr[20];

for (int* i : ip_arr)
{
	i = new int;
	*i = 5;
}

for (int* i : ip_arr)
{
    std::cout << *i << std::endl;
}
That's because at a range-for-loop the elements will be passed as a copy to the loop body. So the value of 'i' will never go inside ip_arr at the first loop.
Hence you need to pass your element by reference:

 
for (int * & i : ip_arr)
Last edited on
Registered users can post here. Sign in or register to post.