简体   繁体   中英

Print error in c lvalue required as unary ‘&’ operand

I am having code error while compiling this

#include <stdio.h>      // standard input / output functions
#include <stdlib.h>
#include <string.h>     // string function definitions
#include <unistd.h>     // UNIX standard function definitions
#include <fcntl.h>      // File control definitions
#include <errno.h>      // Error number definitions
#include <termios.h>   

void main()
{
int USB = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY );         
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);
/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 ) 
{
printf("Error %d form tcgetattr : %d /n",&errno,strerror(errno));
}
}

Error is

USB2UART.c:18:49: error:lvalue required as unary ‘&’ operand
printf("Error %d form tcgetattr : %d /n",&errno,&strerror(errno));
                                         ^

I am using USB to UART conversion and trying to get error with its handler. Hope someone could help. Thanks :)

It looks like that you are trying to apply & at a literal whereas it is applied on a variable and not a literal. Try to remove & and then give it a try.

The C++ standard, §5.3.1,3 says:

The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue [...]

you just don't need the & operator.

if ( tcgetattr ( USB, &tty ) != 0 ) {
    printf( "Error %d form tcgetattr : %s /n", errno, strerror( errno ) );
}

try this

The problem is that you're passing an int pointer to printf for the second and third parameters while it expects an actual int . A lot of people get confused with it at first because scanf requires a pointer but printf doesn't.

So, just remove the & before both errno and strerror(errno) and it should be fine. Like this:

printf("Error %i form tcgetattr : %s \n", errno, strerror(errno));

PS: Also notice I fixed your new-line escape character. It was /n white the correct is \\n .

errno , as defined in the C library, is an int used to report errors.

strerror , in the other hand, is used to get ac string (char *) from the value of errno.

The %d flag of printf needs an int , and &errno is an int * . Replace it by errno

Also, in order to print a char * with printf , you have to use %s, and not %d.

So just replace by this :

printf("Error %d from tcgetattr : %s\n", errno, strerror(errno));

By the way, you should use perror in order to log erros, because it logs errors on stderr.

Using perror, it will look like this :

perror("Error from tcgetattr");

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