Home > Enterprise >  Subtract addresses – Warning: “differs in levels of indirection”
Subtract addresses – Warning: “differs in levels of indirection”

Time:07-02

Why do I receive a warning? pch is already the pointer I got and when I want to subtract the addresses I use &Origi for that.

C4047 '-' : 'char*' differs in levels of indirection from 'char (*)[12]'

// Substring

    char Origi[] = { "Hallo Welt." };
    char* pch = strstr(Origi, "Welt"); // “pch” is a pointer that in this example points 6 characters further than the start of “Origi”.
    printf("%d\n", pch - &Origi);
    printf("%c\n", Origi[pch - &Origi]);

CodePudding user response:

In the snippet:

printf("%d\n", pch - &Origi);

Origi is already of type char* because when you pass an array as argument it decays to a pointer to its first element, passing its address will make it a pointer to array of chars, which is not the same as a pointer to char and will cause a type mismatch in the binary operation.

For the pointer arithmetic to work properly the operands must be of the same type. It should be:

printf("%d\n", pch - Origi);

                |_____|____
                          |
                          ---> same type -> char*

For the second case it's much the same logic, Origi is already a pointer to char. It should be:

printf("%c\n", Origi[pch - Origi]);

                       |_____|____
                                 |
                                 ---> same type -> char*

I'll admit the error issued by msvc is not the best, it should be something like in gcc, for example, which is much more on point:

error: invalid operands to binary - (have 'char* ' and 'char (*)[12]')

Or better yet, in clang:

error: 'char* ' and 'char (*)[12]' are not pointers to compatible types

  • Related