Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes C / C++ and the fly likes errors handling pointers. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Languages » C / C++
Bookmark "errors handling pointers." Watch "errors handling pointers." New topic

errors handling pointers.

Nilushika Udayangani

Joined: Jun 22, 2013
Posts: 8
int* read(){
int i,num,array[11];
printf("enter a integer value between 1 & 10: ");
read() ;

printf("enter %i integers now: ",num);
scanf("%i",*array++);//LINE 12

return array;
why it shows following compile errors when i try to invoke this function, can you please explain me? erros:[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
Mike Blaszczak

Joined: Sep 02, 2013
Posts: 22
In C and C++, an lvalue is anything that can be assigned to; its name comes from anything that can be on the left-hand side of an assignment operator.

Other assignments can involve lvalues implicitly, even though no assignment operator is involved. the ++ operator, for example, assigns a new value to its operand. But the same rules apply:

Your program is violating these rules, hence the error message you get. If we look at the line that's the problem:

we realize that you want to pass a pointer to an integer in the array to scanf() so that scanf() has a place to put the integer it read. Then, you want to increment the pointer so the next time through the loop you have a new place for the next integer.

Problem is, you can't change the "array" variable like that; it's not an lvalue. The way to make your code work would be to get another pointer -- since pointers are lvalues and arrays are not -- and use that, instead. If you initialize that pointer to the first element in the array, you can walk along that array as you expect:

Your function has another serious problem, though: it's returning a pointer to memory that's local to the stack. You'll want to fix that issue, too.

It is sorta covered in the JavaRanch Style Guide.
subject: errors handling pointers.