数组作为数组[n]和指针数组* [英] Array as array[n] and as pointer array*

查看:58
本文介绍了数组作为数组[n]和指针数组*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the difference when array is declared as array[n] or as pointer array* according to example below? I guess that for example both 'a' and 'c' point at the first element of array, but they behave different.

#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;
}

推荐答案

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

Long story short - they are essentially the same, but ever so slightly different.

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

From what I've gathered from http://c-faq.com/aryptr/aryptr2.html , whilst they can both act as a pointer to the front of an array, when you declare an array as

int a[3];

您实际上是将'3'的大小绑定到变量a,以及它是一个数组的事实.因此,当您尝试将大小为5的b分配给a时,会出现编译错误.

you are essentially binding the size of '3' to your variable a, along with the fact it's an array. Hence, when you try to assign b, of size 5 to a, you get a compilation error.

相反,当您写作

int * a;

您只是在说这是一个可以指向数组的指针",没有任何关于大小的保证.

You are merely saying 'this is a pointer that may point to an array', with no promise on the size.

微妙的,不是吗?

这篇关于数组作为数组[n]和指针数组*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆