微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 有什么区别?指向数组与正常数组的指针

我熟悉 Java,并尝试教自己C/C++.我正在从一个正在托管材料 here的课程中窃取一些课程.我不幸的是不能问老师,因为我不在课堂上.我关心的是“动态声明数组”下的部分:

If you
want to be able to alter the size of
your array at run time,then declare
dynamic arrays. These are done with
pointers and the new operator. For the
basics on pointers,read the pointers
section.

Allocate memory using new,and then
you access the array in the same way
you would a static array. For example,

int* arrayPtr = new int[10]; for
(int i = 0; i < 10; i++) {
arrayPtr[i] = i; }

The memory picture is identical to the
static array,but you can change the
size if you need to. Don’t forget you
must deallocate the memory before
allocating new memory (or you will
have a memory leak).

delete [] arrayPtr; // the []
is needed when deleting array pointers
arrayPtr = new int[50]; . . .

When you’re completely done with the
array,you must delete its memory:

delete [] arrayPtr;

Dynamic multi-dimensional arrays are
done in a similar manner to Java. You
will have pointers to pointers. For an
example,see a

我的理解是,C中的数组只是引用数组中第一个元素的内存地址.

那么int * pointerarray = new int [10]有什么区别?和int数组[10];如果有的话

我做了一些测试,似乎表明他们做同样的事情.网站错了还是我读错了?

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc,char** argv) {

    // Initialize the pointer array
    int *pointerarray = new int[10];
    for (int i = 0; i < 10; i++){

        pointerarray[i] = i;
    }

    // Initialize the regular array
    int array[10];
    for (int i = 0; i < 10; i++){

        array[i]= i;
    }

    cout << *(pointerarray + 5) << endl;
    cout << *(array + 5) << endl;

    cout << pointerarray[5] << endl;
    cout << array[5] << endl;

    cout << pointerarray << endl;
    cout << array << endl;

    return 0;
}

输出

5
5
5
5
0x8f94030
0xbfa6a37c

我试图按照网站上的描述“动态地重新调整”我的指针数组,但是我的新(较大)指针数组最后填满了0,这不是很有用.

解决方法

int array [10];静态地声明数组大小,这意味着它是固定的 – 这是唯一的主要区别.它也可能被分配到功能的堆栈帧内,即在程序的堆栈上.你不需要担心在这种数组上使用delete [],实际上如果你删除它,你可能会崩溃程序.

当您使用operator new时,您可以动态分配内存,这可能较慢,内存通常来自堆,而不是程序的堆栈(尽管并非总是).这在大多数情况下更好,因为堆栈空间比堆空间更受限制.但是,当您不再需要它时,您必须注意内存泄漏并删除[]您的东西.

至于你的数组充满了零,你的课堂材料没有说,你必须这样做:

int *arr = new int[20]; // old array
//do magic here and decide that we need a bigger array
int *bigger = new int[50]; // allocate a bigger array
for (int i = 0; i < 20; i++) bigger[i] = arr[i]; // copy the elements from the old array into the new array
delete[] arr;
arr = bigger;

代码将阵列arr再增加30个元素.请注意,您必须将旧数据复制到新数组中,否则它将不会存在(在您的情况下,所有内容都将变为0).

原文地址:https://www.jb51.cc/c/115584.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐