簡體   English   中英

一元'&'操作數所需的c左值中的打印錯誤

[英]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則不需要。

因此,只需在errnostrerror(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM