[英]Print error in c lvalue required as unary ‘&’ operand
编译时出现代码错误
#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));
}
}
错误是
USB2UART.c:18:49: error:lvalue required as unary ‘&’ operand
printf("Error %d form tcgetattr : %d /n",&errno,&strerror(errno));
^
我正在使用USB到UART的转换,并尝试使用其处理程序出错。 希望有人可以帮忙。 谢谢 :)
看起来您正在尝试将&
应用于文字,而将其应用于变量而不是文字。 尝试删除&
,然后尝试一下。
C ++标准§5.3.1,3指出:
一元&运算符的结果是指向其操作数的指针。 操作数应为左值[...]
您只是不需要&运算符。
if ( tcgetattr ( USB, &tty ) != 0 ) {
printf( "Error %d form tcgetattr : %s /n", errno, strerror( errno ) );
}
尝试这个
问题在于,您正在将int
指针传递给第二个和第三个参数的printf
,而它期望一个实际的int
。 起初,很多人对此感到困惑,因为scanf
需要一个指针,而printf
则不需要。
因此,只需在errno
和strerror(errno)
之前都删除&
,就可以了。 像这样:
printf("Error %i form tcgetattr : %s \n", errno, strerror(errno));
PS:另外请注意,我修复了您的换行符。 是/n
白色正确是\\n
。
C库中定义的errno
是用于报告错误的int。
另一方面, strerror
用于从errno的值获取ac字符串(char *)。
printf
的%d标志需要一个int
, &errno
是一个int *
。 用errno
替换
另外,为了使用printf
打印一个char *
,您必须使用%s,而不是%d。
因此,只需替换为:
printf("Error %d from tcgetattr : %s\n", errno, strerror(errno));
顺便说一句,您应该使用perror来记录错误,因为它会在stderr上记录错误。
使用perror,它将看起来像这样:
perror("Error from tcgetattr");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.