我需要檢查指標陣列的元素是否NULL存在。我試圖撰寫如下代碼,但編譯器給了我一個錯誤。
struct Example {
float number1;
int number2;
};
typedef struct Example Example;
static Example *array[3] = { NULL }; //inizialized array to NULL
for (int i = 0; i < 3; i ) {
if (array[i] == NULL) {
/*code*/
break;
}
}
這是我得到的錯誤:
"error: invalid operands to binary == (have ‘Example’ and ‘void *’)"
參考線
if (array[i] == NULL) {
我究竟做錯了什么?
更新
該for回圈最初位于另一個將指標陣列作為引數的函式中。
static void fun(Example *array) {
for (int i = 0; i < 3; i ) {
if (array[i] == NULL) {
/*code*/
break;
}
}
}
但它一直給我同樣的錯誤,盡管型別實際上Example*不是Example. 相反,如果我寫Example** array為引數,它會接受代碼并且不會給我任何錯誤。
static void fun (Example **array) {
for (int i = 0; i < 3; i ) {
if (array[i] == NULL) {
/*code*/
break;
}
}
}
有人可以向我解釋為什么編譯器想要Example**而不是Example*嗎?
完整代碼
下面是完整的代碼,在2檔:file.c和file.h。
檔案.h:
#include <stdio.h>
#include <stdbool.h>
struct Example {
float number1;
int number2;
};
typedef struct Example Example;
檔案.c
#include <stdio.h>
#include <stdlib.h>
#include "file.h"
static Example *array[3] = { NULL }; //inizialized array to NULL
static void fun(Example *);
static void fun(Example *array) {
for (int i = 0; i < 3; i ) {
if (array[i] == NULL) {
/*code*/
break;
}
}
}
int main(void) {
fun(array);
return 0;
}
錯誤:
gcc -c file.c -std=c11 -Wall
file.c: In function ‘fun’:
file.c:10:28: error: invalid operands to binary == (have ‘Example’ and ‘void *’)
10 | if(array[i] == NULL){
| ~~~~~~~~ ^~
| |
| Example
file.c: In function ‘main’:
file.c:20:9: warning: passing argument 1 of ‘fun’ from incompatible pointer type [-Wincompatible-pointer-types]
20 | fun(array);
| ^~~~~
| |
| Example **
file.c:8:26: note: expected ‘Example *’ but argument is of type ‘Example **’
8 | static void fun(Example* array){
| ~~~~~~~~~^~~~~
uj5u.com熱心網友回復:
首先,您應該知道在您的程式中,您有兩個不同的變數,名稱分別為array:
- 該名稱的全域變數。
- 函式的區域變數(函式引數)
fun。
在函式內部fun,區域變數array會覆寫同名的全域變數,這意味著當你array在函式內部撰寫時,你將參考區域變數,而不是全域變數。為防止混淆,您可能希望對兩個變數使用不同的名稱。
編譯器抱怨以下行:
if(array[i] == NULL){
如前所述,array在函式內部使用識別符號fun將參考函式引數,而不是全域變數。
在 的函式定義中fun,您將函式引數的型別定義array為Example *。因此,使用取消參考此型別array[i]將為您提供一個型別為 的變數Example。這意味著在 中array[i] == NULL,您正在嘗試將 astruct Example與值進行比較NULL。這沒有意義,也是您收到編譯器錯誤的原因。
與其將函式引數定義array為 type Example*,您可能希望它為 type Example**,因為您希望它指向陣列的第一個元素,該元素本身就是指向 a 的指標struct Example。換句話說,您希望函式引數是指向指標的指標。因此,您還應該將其宣告為:
static void fun( Example **array ){
或者也許更好:
static void fun( Example *array[] ){
這兩行就編譯器而言是等效的,但第二行可能更好,因為它清楚地表明指標不是指向單個變數,而是指向陣列。
該運算式array[i] == NULL現在有意義,因為它現在將Entity*與進行比較NULL。
將此更改應用于 的函式定義后fun,并將其應用于函式的前向宣告后,您的代碼將被干凈地編譯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/394535.html
上一篇:為什么指標在C中列印兩次?
