数组初始化函数 [英] Array initialization functions
问题描述
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 Please help me understand the problem with this. Yes, I know I should use When you pass or return the pointer like1 and try it again. I recommend the second method due to its higher expressiveness: something like does not make clear if does. 1 as noted by @Jack in the comments to this answer 这篇关于数组初始化函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!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;
}
std::vector
but I want to understand why this doesn't work :)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 tovoid initialize(int*& array, int size)
int* initialize(int size)
initialize(array, 3);
array
is modified or not. OTOH,int* array = initialize(3);