gpt4 book ai didi

c++ - 数组作为数组 [n] 和指针数组*

转载 作者:太空狗 更新时间:2023-10-29 20:46:45 25 4
gpt4 key购买 nike

根据下面的示例,将数组声明为数组[n] 或指针数组* 有什么区别?我想,例如 'a' 和 'c' 都指向数组的第一个元素,但它们的行为不同。

#include <iostream>

int main() {
int a[3] = {1};
int b[5];
std::cout << *a << std::endl; //prints 1 - ok
//a = b; //error during compilation

int* c = new int[3];
c[0] = 2;
int* d = new int[5];
std::cout << *c << std::endl; //prints 2 - ok
c = d; //works ok!

return 0;
}

最佳答案

长话短说 - 它们本质上相同,但略有不同。

根据我从 http://c-faq.com/aryptr/aryptr2.html 收集到的信息, 虽然当您将数组声明为

时,它们都可以充当指向数组前面的指针
int a[3];

您实际上是将“3”的大小绑定(bind)到您的变量 a,同时它是一个数组。因此,当您尝试将大小为 5 的 b 分配给 a 时,会出现编译错误。

相反,当你写的时候

int * a;

您只是在说“这是一个可能指向数组的指针”,对大小没有任何保证。

很微妙,不是吗?

关于c++ - 数组作为数组 [n] 和指针数组*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7417556/

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