简体   繁体   中英

c++ overload operator Dynamic and Static array

I have class that has private array and pointer. I have 3 constructors, one is a copy constructor other that takes pointer to array as a parameter. I am overloading operators, for example << , ostream. When I am passing a pointer to static array to my class my program working fine. But when I am starting to use dynamic array, my function operated weird and output some crazy data. What is a difference I should make in program so operator will work with both Static and Dynamic arrays? I have a separate function that create dynamic array random() and return pointer which I am passing as a parametr. Here my code

With the assumption that ptr is a member in the HugeInteger class, you have a couple of cases of undefined behavior .

In the case of the default constructor you make ptr point to a local array. This array, like all local variables, have its scope only in the function it is declared. So when the default constructor returns the member variable ptr is "dangling".

In the case of the copy-constructor, you don't allocate memory that ptr can point to. So when indexing it you are indexing an undefined memory location.


As for your problem it's basically the same as for the default constructor. You assign pointer to point to the local array arr . When the function returns the array no longer exists, so the pointer points to unused memory, and that have may been used by other functions. Also, what you're doing there is not creating a dynamic array, that would involve allocating memory with new .

At

int * pointer;
int arr[40]={0};
pointer = arr;

pointer will be an array of 40 bytes. This array is not dynamically allocated and will be completely removed at the end of the function. Change your function to this:

int* random()
{
    int * pointer = new int[40];
    cout << "Random function: ";
    for(int j = 0; j < 40; j++){
        pointer[j] = rand()%10; cout << pointer[j];
    }
    cout << endl;
    return pointer;
}

This way you will keep the values of pointer and you can use them in other functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM