Reputation: 21
New C++ learner here.
I am trying to build a struct whose member variables are 2 dynamically allocated int arrays. The arrays are filled by std::cin.
#include <iostream>
struct foo
{
int* x;
int* y;
};
// Everything from here goes into the main()
unsigned int numArray;
std::cin >> numArray;
int* m = new int[numArray];
int* n = new int[numArray];
for(int z = 0; z < numArray; z++)
{
std::cin >> m[z];
}
for(int z = 0; z < numArray; z++)
{
std::cin >> n[z];
}
foo* bar = new foo;
bar->x = m;
bar->y = n;
delete[] m;
delete[] n;
This should have created a struct foo named bar
, with the member variables m
(int array) and n
(int array).
My questions start here:
Inputs:
5 // length of the array
1 2 3 4 5 // for array int* x
6 7 8 9 10 // for array int* y
When I try to print the results with std::cout, however...
for(int z = 0; z < 5; z++)
{
std::cout << (bar->x)[z] << " ";
}
std::cout << std::endl;
for(int z = 0; z < 5; z++)
{
std::cout << (bar->y)[z] << " ";
}
std::cout << std::endl;
I get this.
0 2 3 4 5
146890752 7 8 9 10
My guess is that either 1. I built the array wrong or 2. I'm accessing the array wrong (or maybe both?), but I have no idea what to do. The first item in array x always seems to be 0 while the first item in array y seems to be some random large number. What's going on?
Upvotes: 0
Views: 249
Reputation: 46
By using the delete[]
function, you "deallocated" the memory, but it doesn't necessarily rewrite the data immediately. Deleting just frees it up. It rewrites the first one, but it's a shallow copy, copied only by address. Though it might be a memory leak of unallocatable memory until the program terminates; that does happen sometimes.
Upvotes: 0
Reputation: 141574
You deleted those arrays with delete[] m; delete[] n;
. Then the rest of your code goes on to access deleted memory which causes undefined behaviour.
Maybe you misunderstand bar->x = m;
. After that line, the two pointers bar->x
and m
both point to the same array of ints. Then you delete[]
that array, leaving both pointers pointing to the deleted array (technically, both pointers are indeterminate).
If you remove those delete statements then your code should work better.
NB. If you have further questions then update your post to include your exact code, instead of describing it (e.g. int main() {
instead of "into the main").
Upvotes: 3