减去地址–警告:“在间接级别上有所不同”

发布于 2025-02-10 09:42:01 字数 466 浏览 2 评论 0原文

为什么我会收到警告? PCH已经是我获得的指针,当我想减去地址时,我使用& origi

c4047' - ':'char*'间接水平与'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]);

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]);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你是我的挚爱i 2025-02-17 09:42:01

在摘要中:

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

origi已经是类型的char*,因为当您将数组作为参数传递时,它会衰减到指向其第一个元素的指针时,传递其地址将使它成为一个指向一系列字符的指针,它与char的指针不同,并且会导致二进制操作中的类型不匹配。

为了使指针算术正常工作,操作数必须具有相同的类型。应该是:

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

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

对于第二种情况,它的逻辑几乎是相同的,origi已经是指向char的指针。应该是:

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

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

我承认MSVC发出的错误不是最好的,例如,它应该像GCC中一样,这更多的是:

错误:无效的操作数是二进制 - (拥有'char* '和'char (*)[12]')

或更好的是,在Clang中:

错误:'char* '和'char (*)[12]'不是兼容类型的指示

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文