Dynamic Arrays passing to functions

女生的网名这么多〃 提交于 2019-12-11 03:33:44

问题


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";
} 

回答1:


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 ?




回答2:


Set this signature for the function

void func(string * & arr, string * & brr)



回答3:


@cnicutar correctly diagnosed the problem; you'll either need to pass arr by reference (reference to the POINTER, not the array), of have fund return the new value of arr, which the caller can assign.



来源:https://stackoverflow.com/questions/9167540/dynamic-arrays-passing-to-functions

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