"Warning comparison between pointer and integer" - what is it?

While compiling the code in C language I got this error:

[Warning] comparison between pointer and integer

Regarding this code Step:

    if(livro > TAM) {
        printf("------- Você já cadastrou o maximo de livros ! -------");
    }

Being livro a struct:

struct fichaLivro {
    int cod;
    char obra[50];
    char autor[50];
    char editora[50];
}livro[TAM];

And TAM a constant:

#define TAM 5

What is happening and how can I solve it?

Author: Maniero, 2019-07-01

1 answers

The error is exactly what is written, as you declared the variable livro as a array, it becomes a pointer to a data sequence, since TAM is a numeric constant.

C is a static typing language, but weak, so it even lets you make comparisons even if it doesn't make sense, in a pointer and a simple number are two completely different things it's like you want to know if an Apple and a horse are the same thing, you can't even start compare, then most compilers warn that this will produce a meaningless result. The solution is to compare things that make sense, but we don't even know exactly what would make sense there, what you're trying to compare, the only sure thing is that a book can be compared to a 5.

Looking at the whole code in another question you might want to compare the id of the book, something like this:

if (livro.id > TAM) {

But then book would have to have only one book and not a array of books (which alias the variable should call livros and not livro.

If you're actually going to work with the array , you might be inside a loop and want to do something like this:

if (livro[i].id > TAM) {

But if there is a loop maybe I wanted to do if (i > TAM) {.

But it may be that all options are wrong because the concept is wrong and it shouldn't even do this.

After editing it is seen that the problem should not even exist. The code is already running to register the size maximum, does not allow to register less than the maximum, nor more, so this if all does not make sense, even if you create a control, which is the third option I had given above, it will never enter this if, so just take it out.

I'm not even going to try to show another way to do it better because I already know that you prefer to do it your way, even if it's not good.

 4
Author: Maniero, 2019-07-01 02:52:14