声明 int 数组 [英] Declaring array of int

查看:43
本文介绍了声明 int 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个声明有什么区别吗?

Is there any difference between these two declarations?

int x[10];

对比

int* x = new int[10];

我想前一个声明(就像后一个)是一个指针声明,两个变量可以被同等对待.这是否意味着它们本质上是相同的?

I suppose the former declaration (like the latter one) is a pointer declaration and both variables could be treated the same. Does it mean they are intrinsically the same?

推荐答案

#include<iostream>    

int y[10];


void doSomething()
{
    int x[10];
    int *z  = new int[10];
    //Do something interesting

    delete []z;
}

int main()
{
    doSomething();

}

int x[10]; 

- 在堆栈上创建一个大小为 10 个整数的数组.
- 您不必显式删除此内存,因为它会随着堆栈展开而消失.
- 它的范围仅限于函数 doSomething()

int y[10];

- 在 BSS/Data 段上创建一个大小为 10 的整数数组.
- 您不必明确删除此内存.
- 因为它被声明为global,所以它可以被全局访问.

- Creates an array of size 10 integers on BSS/Data segment.
- You do not have to explicitly delete this memory.
- Since it is declared global it is accessible globally.

int *z = new int[10];

- 在堆上分配大小为 10 个整数的动态数组,并将此内存的地址返回给 z.
- 使用后必须明确删除此动态内存.使用:

delete[] z;

这篇关于声明 int 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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