Mads Marquart
Mads Marquart

Reputation: 500

Array initialization functions

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 :)

Upvotes: 2

Views: 12962

Answers (3)

cadaniluk
cadaniluk

Reputation: 15229

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

Upvotes: 18

Pravin Battu
Pravin Battu

Reputation: 1

Pass the address of the pointer to avoid the error message

Upvotes: 0

dspfnder
dspfnder

Reputation: 1123

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);

Upvotes: 0

Related Questions