数组初始化函数 [英] Array initialization functions

查看:146
本文介绍了数组初始化函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩C ++,偶然发现了这个问题。我试图在堆上初始化一个数组指针,它在 initialize()内部工作,在那里输出 69 ,但是在 main()中,它会崩溃,出现错误 EXC_BAD_ACCESS

  #include< iostream> 

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

//测试
array [2] = 69;
std :: cout<<数组[2]<<的std :: ENDL; //工作正常
}

int main(){

int size = 3;
int * array;

//初始化
initialize(array,size);

//测试
std :: cout<<数组[2]<<的std :: ENDL; // Crash,EXC_BAD_ACCESS

//清理
delete [] array;
array = nullptr;


return EXIT_SUCCESS;
}

请帮我理解这个问题。



是的,我知道我应该使用 std :: vector 但我想明白为什么这不起作用:当你将数组传递给函数时,的指针被制成。当您将 new int [size]; 赋值给 array 时,您可以将其实际分配给参数,即副本我在说。要真正修改 main 中定义的数组<$ code>,请使用引用。将函数的定义改为

  void initialize(int *& array,int size)

或返回指针如 1

  int * initialize(int size)

然后再试一次。




我推荐第二种方法,因为它具有较高的表现力:类似于

  initialize(array,3); 

并不清楚 array 是否被修改或不。 OTOH,

  int * array = initialize(3); 

不会。






1 由@Jack在这个答案的评论中注明

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

解决方案

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

这篇关于数组初始化函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆