简体   繁体   中英

Calling scanf() gives error “ISO C++ forbids cast to non-reference type used as lvalue”

I have this code:

int* read(){
int i,num,array[11];
printf("enter a integer value between 1 & 10: ");
scanf("%i",&num);
while(!(num>0&&num<11)){
read() ;
}

if(num>0&&num<11){
printf("enter %i integers now: ",num);
for(i=0;i<num;i++)
scanf("%i",*array++);//LINE 19 is here..........

*array=0;
}
return array;
}

It shows the following compiler errors when I try to invoke this function:

[Error] C:\Users\seeker-PC\Documents\C-Free\Projects\n\Untitled12.cpp:19: error: ISO C++ forbids cast to non-reference type used as lvalue
[Error] C:\Users\seeker-PC\Documents\C-Free\Projects\n\Untitled12.cpp:19: error: non-lvalue in assignment

Can you please explain what is going wrong?

 scanf("%i",*array++); 

That line makes little sense. You probably meant:

scanf("%i", &array[i]);

To start with ,

array names are not modifiable lvalue so doing increment operations on them are illegal. So you should better change

scanf("%i",*array++);

to

scanf("%i", &array[i]);

scanf takes the address of the variable for assigning the value so using & in this case is necessary well atleast in this case.

Useful advice- Use proper indentation in your code and please put spaces between tokens ,it doesn't seem important at first but it gives less headaches to people who read your code and IMHO you definitely write code for others , don't you ?

You have 2 major errors in this line.

Operator ++ modifies the operand. The operand here is array and it's a non-modifiable address of an array. Hence the compiler error.

Second error is related to the usage of scanf . scanf requires an address for data storage.

To overcome these errors you should use either scanf("%i", &array[i]); or (if you want to be closer to the original syntax for some reason) - scanf("%i", arrayPtr++); where arrayPtr is initialized to &array[0] .

Use this. Have just included the main() function to make it runnable.

#include <stdio.h>
int* read(){
int i,num,array[11];
printf("enter a integer value between 1 & 10: ");
scanf("%d",&num);
while(!(num>0&&num<11)){
read() ;
}

if(num>0&&num<11){
printf("enter %i integers now: ",num);
for(i=0;i<num;i++)
scanf("%d",&array[i]);//LINE 12 is here..........

*array=0;
}
return array;
}
int main()
{
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM