Weird Error: invalid initialization of non-const reference of type 'int*&' from a temporary of type 'int*'

Hi! I get this error on line 10 (emboldened) in the code below. I don't understand what the term 'temporary' means. I'd be really grateful if someone could explain where I've gone wrong, thanks.

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

void print(int*);
void doubleValuesInArray(int*&);//LINE 4

int main()
{
    int i[] = {1,2,3,4,5,6,7,8,9,10};
    print(i);
    doubleValuesInArray(i);//LINE 10
    print(i);
    return 0;
}

void print(int* i)
{
for(;i;i++)
    std::cout<<*i<<std::endl;
}

void doubleValuesInArray(int*& j)
{
    for(;j;j++)
        *j = (*j)*2;
}


Errors

main.cpp:10: error: invalid initialization of non-const reference of type 'int*&' from a temporary of type 'int*'

main.cpp:4: error: in passing argument 1 of 'void doubleValuesInArray(int*&)'
Last edited on
You don't need to pass arrays as reference variables, as in using the "&" when declaring them they are automatically passed as reference, try taking it out see if the error is fixed.
I don't get that error anymore, but now I get a segmentation fault and I think it's because of the'for' loops. Correct me if I'm wrong but in the code:

1
2
for(;i;i++)
    std::cout<<*i<<std::endl;


when the for loop is done traversing all the element of the array, shouldn't it come across a '\0' and terminate
That is incorrect.

For loops operate like so:
for( initialize; condition; increment )

as long as 'condition' is true (nonzero), the loop will keep going.

Take a look at your for loop:

 
for(;i;i++)


Your condition is i. So the loop will keep looping until i becomes zero. Since i is a pointer, this means it will keep looping until i becomes a null pointer (which won't happen until LONG after it reaches the end of the array.

You probably wanted your loop condition to be *i, since that will check to see if the data i points to is zero or not.
I've never seen for loops written in the way you are writing them, it may be proper syntax but I have not seen it.

For reading out an array usually a loop would be written as such

for(int i = 0, i < "size of the array"; i++)
I've never seen for loops written in the way you are writing them, it may be proper syntax but I have not seen it.


I saw this technique only recently too, and i'm trying to practice it.

You probably wanted your loop condition to be *i, since that will check to see if the data i points to is zero or not.


You're right, that got it working. Just one last thing:

I get the numbers printed out fine, but there are two extra weird numbers at the end e.g.
1 2 3 4 5 6 7 8 9 10 19970364676 4215776. Why does that happen?
Sorry if it's a dumb question.
Topic archived. No new replies allowed.