new int[3] 会对 int 指针做什么?

阿佩特拉

我一直在寻找指针的用途,结果这就是其中之一。动态分配内存。我对关键字new,以及最后添加 [number] 时有点困惑new int[3]. 我确实理解这个问题可能很糟糕。我才13岁。

   #include <iostream>
    using namespace std;
    int main() {
        int* scores;
        cout << "Enter top 3 scores: ";
    
        //dynamically allocate memory
        scores = new int[3];
        for (int i = 0; i < 3; i++) {
            "Enter score: ";
            cin >> scores[i];
        }
        cout << endl << "Scores are: ";
        for (int i = 0; i < 3; i++) {
            cout << scores[i] << " ";
        }
        delete[] scores;
    
        return 0;
    }
彼得雷克

指针基本上是指向内存中特定地址的变量。数组是在内存中连续分配的一组变量。当您编写时,scores = new int[3]您为三个 int 类型变量分配了一块内存,并使scores变量引用第一个地址。现在,在引用数组 fields: 时scores[i],获取数组第一个字段的地址并添加变量i,从而为您提供i第 th 个元素的地址

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章