动态数组传递给函数 [英] Dynamic Arrays passing to functions
问题描述
我在主函数创建2动态数组。我已经按引用传递两者的功能。然后,我从较小的动态数组数据复制到更大的动态数组。我删除较小的动态数组。较大的动态数组的地址分配给较小的动态数组。现在最好的ARR数组应具有的10大小然而,当我尝试打印主数组的第6要素,它崩溃。请看看下面的code:
的#include<&iostream的GT;
#包括LT&;串GT;使用命名空间std;无效FUNC(字符串*改编,串* BRR);诠释的main()
{
字符串* ARR =新的字符串[5];
改编[0] =hello0;
改编[1] =hello1;
ARR [2] =hello2;
改编[3] =hello3;
改编[4] =hello4; 字符串* BRR =新的字符串[10];
FUNC(ARR,BRR); 的for(int i = 0;我6;;我++)
COUT<<改编[1] - ;&下; ENDL; 返回0;
}无效FUNC(字符串*改编,串* BRR)
{
的for(int i = 0;我小于5;我++)
BRR [I] =改编[I] 对于(I = 0; I&小于5;我+ +)
COUT<< BRR [1] - ;&下; ENDL; 删除[] ARR; ARR = BRR; 改编[5] =hello5;
}
这行有呼叫者绝对没有任何影响:
改编= BRR;
所以,通话结束后, 改编
点究竟在何处使用点之前 - 到现在是无效的内存区域(因为你已经删除)
如果这将是一个C的问题,我会建议你用一个指针的指针(字符串**改编
)。不过,我觉得这是一个C ++程序讨厌。也许你想的地方使用参考?
I have created 2 dynamic arrays in the main function. I have passed both of them to the function by reference. Then I copy data from smaller dynamic array to the larger dynamic array. I delete the smaller dynamic array. Assign the address of the larger dynamic array to the smaller dynamic array. Now ideally the arr array should have size of 10. However, when I try to print the 6th element of the array in the main, it crashes. Please have a look at the code below:
#include <iostream>
#include <string>
using namespace std;
void func(string * arr, string * brr);
int main()
{
string* arr = new string[5];
arr[0] = "hello0";
arr[1] = "hello1";
arr[2] = "hello2";
arr[3] = "hello3";
arr[4] = "hello4";
string* brr = new string[10];
func(arr, brr);
for(int i = 0; i < 6; i++)
cout << arr[i] << endl;
return 0;
}
void func(string * arr, string * brr)
{
for(int i = 0; i < 5; i++)
brr[i] = arr[i];
for(i = 0; i < 5; i++)
cout << brr[i] << endl;
delete []arr;
arr = brr;
arr[5] = "hello5";
}
This line has absolutely no effect for the caller:
arr = brr;
So after the call, arr
points exactly where it used to point before - to a now invalid memory area (because you deleted it).
If this would be a C question, I would advise you to use a pointer to a pointer (string **arr
). However, I feel this is nasty in a C++ program. Maybe you want to use a reference somewhere ?
这篇关于动态数组传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!