gpt4 book ai didi

c++ - `*a` 和 `a[0]` 有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 22:33:00 26 4
gpt4 key购买 nike

给定一个用户自定义类型A,和一个指针A* a*a有什么区别一个[0]

(虽然*(a+0)/a[0]被定义为等价的,但*a/a[0],其中细微的差别可能会在某些情况下导致编译错误。)

最佳答案

如果 A 是不完整类型,则 *a 有效,但 a[0] 无效,in this example :

struct A;

void foo(A& r)
{
}

void bar(A* a)
{
foo(*a);
foo(a[0]); // error: invalid use of incomplete type ‘struct A’
}

那是因为 a[0] 等价于 *(a+0),但是你不能向指向不完整类型对象的指针添加一些东西(甚至零),因为指针算法需要知道大小。

关于c++ - `*a` 和 `a[0]` 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14487726/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com