减去地址–警告:“在间接级别上有所不同”
为什么我会收到警告? 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在摘要中:
origi
已经是类型的char*
,因为当您将数组作为参数传递时,它会衰减到指向其第一个元素的指针时,传递其地址将使它成为一个指向一系列字符的指针,它与char的指针不同,并且会导致二进制操作中的类型不匹配。为了使指针算术正常工作,操作数必须具有相同的类型。应该是:
对于第二种情况,它的逻辑几乎是相同的,
origi
已经是指向char
的指针。应该是:我承认MSVC发出的错误不是最好的,例如,它应该像GCC中一样,这更多的是:
或更好的是,在Clang中:
In the snippet:
Origi
is already of typechar*
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:
For the second case it's much the same logic,
Origi
is already a pointer tochar
. It should be: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:
Or better yet, in clang: