指针作为C ++结构中的成员数据字段

时间:2019-06-20 10:11:56

标签: c++ pointers struct

#include <iostream>
using std::cout;
using std::cin;

void printArray(int A[], int size) {
    for(int i = 0; i < size; i++) {
        cout << A[i] << "\t";
    }
    cout << "\n";
}

struct Array {
    int *A;
    int size;
    int length;
};

void display(Array *arr) {
    for(int i = 0; i < arr->length; i++) {
        cout << arr->A[i] << "\t";
    }
    cout << "\n";
}

void fillArray(Array *arr) {
    for(int i = 0; i < arr->length; i++) {
        cin >> arr->A[i];
    }
}

void add(Array *arr, int x) {
    if(arr->length < arr->size) {
        arr->A[++arr->length] = x;
    }
}

int main() {
    Array arr;
    cout << "arr.size before initializing: " << arr.size << "\n"; // gives a garbage value
    cout << "Enter the size of the array: ";
    cin >> arr.size;
    cout << "Output of arr variable &arr: " << &arr << "\n";
    arr.A = new int[arr.size];
    cout << "arr.length before initializing: " << arr.length << "\n"; // gives garbage value
    cout << "How many elements do you want to enter: ";
    cin >> arr.length;
    fillArray(&arr); //This is not pass by value but pass by reference because 
    display(&arr); // this function displays the values of arr
    add(&arr, 15);
    cout << "The length of the array after adding: " << arr.length << "\n";
    display(&arr);
    printArray(arr.A, arr.length);
}

该程序的输出如下:

$ ./array_adt 
arr.size before initializing: -140717888
Enter the size of the array: 10
Output of arr variable &arr: 0x7ffe4e0ec040
arr.length before initializing: 21932
How many elements do you want to enter: 5
4 6 7 3 2 
4   6   7   3   2   
The length of the array after adding: 6
4   6   7   3   2   0   
4   6   7   3   2   0

我很困惑为什么不将元素15添加到该结构的数组(实际上是一个初始化为堆中数组的指针)。如果有人可以对此有所了解,那么这对于许多人以及深入理解c ++概念都非常有用。
非常感谢。

1 个答案:

答案 0 :(得分:3)

arr->A[++arr->length] = x;

应该是

arr->A[arr->length++] = x;

数组索引在C ++中从零开始,因此大小为arr的数组N的第一个元素末尾arr[N]。换句话说,15确实添加到了数组中,只是位置不正确。

您的代码还会泄漏内存,因为从未删除main中分配的数组。正确分配动态内存是一个很大(也是非常重要)的话题。请查阅您最喜欢的C ++书籍,尤其是应该研究rule of three