I need to check if an element of an array of pointers is NULL or not.
I tried to write the code as following, but the compiler gives me an error.
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;
}
}
This is the error I get:
"error: invalid operands to binary == (have ‘Example’ and ‘void *’)"
referred to the line
if (array[i] == NULL) {
What am I doing wrong?
UPDATE
The for loop was originally inside another function that took as parameter the array of pointers.
static void fun(Example *array) {
for (int i = 0; i < 3; i++) {
if (array[i] == NULL) {
/*code*/
break;
}
}
}
But it keeps giving me the same error, despite the fact that the type is actually Example* and not Example.
Instead, if I write Example** array as parameter, it accepts the code and doesn't give me any error.
static void fun (Example **array) {
for (int i = 0; i < 3; i++) {
if (array[i] == NULL) {
/*code*/
break;
}
}
}
Can someone explain to me why does the compiler wants Example** and not Example* ?
FULL CODE
Here's the full code, in 2 files: file.c and file.h.
file.h:
#include <stdio.h>
#include <stdbool.h>
struct Example {
float number1;
int number2;
};
typedef struct Example Example;
file.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;
}
ERROR:
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){
| ~~~~~~~~~^~~~~
array[i]is of typeExample *, but the error message claims that it is of typeExample