Array initialization functions

人盡茶涼 提交于 2019-12-02 05:32:39

问题


I was playing around with C++ and I stumbled upon this problem. I'm trying to initialize an array pointer on the heap, and it works inside the initialize(), where it outputs 69, but in the main(), it crashes with the error EXC_BAD_ACCESS.

#include <iostream>

void initialize(int* array, int size) {
    array = new int[size];

    // Testing
    array[2] = 69;
    std::cout << array[2] << std::endl; // Works fine
}

int main() {

    int size = 3;
    int* array;

    // Initializing
    initialize(array, size);

    // Testing
    std::cout << array[2] << std::endl; // Crash, EXC_BAD_ACCESS

    // Cleanup
    delete[] array;
    array = nullptr;


    return EXIT_SUCCESS;
}

Please help me understand the problem with this.

Yes, I know I should use std::vector but I want to understand why this doesn't work :)


回答1:


When you pass array to the function, a copy of that pointer is made. When you assign new int[size]; to array, you assign it actually to the argument, which is the copy I was talking about. To really modify the array defined in main, use references. Change the definition of the function to

void initialize(int*& array, int size)

or return the pointer like1

int* initialize(int size)

and try it again.


I recommend the second method due to its higher expressiveness: something like

initialize(array, 3);

does not make clear if array is modified or not. OTOH,

int* array = initialize(3);

does.


1 as noted by @Jack in the comments to this answer




回答2:


The reason why the program fails is because you want the memory to be allocated outside the initialize function and the function to operate on that memory.

Simply remove the new statement from your function so that it looks like this...

void initialize(int* array, int size) {
        for (int i = 0; i < size; i++) {
        cout << array[i] << " ";
    }
}

... then, do your allocation in main and just before the function call...

int size = 3;
int* array = new int [size];

initialize(array, size);



回答3:


Pass the address of the pointer to avoid the error message



来源:https://stackoverflow.com/questions/33243436/array-initialization-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!