I'm fairly-new to C++, but have experience in higher-level languages. Just trying to self-teach. I've been working on this issue for a few days (off and on) and cannot seem to figure out what is happening here. I know it is something fundamental about C/C++ that I should understand. The problem:
I am storing a pointer to an array in a struct (stripped down):
namespace TestSpace {
struct ArrayData {
double *data;
int count;
};
}
In the same file, I have a function:
struct ArrayData *unsorted_5count_duplicates() {
struct ArrayData *arr;
double data[] = { 3.5, 1.2, 1.2, 4.0, 3.5 };
arr = (ArrayData *)calloc(1,sizeof(*arr));
//I added this line in attempt to fix the problem... no such luck.
arr->data = (double *)calloc(5,sizeof(double));
arr->data = data;
arr->count = 5;
return arr;
}
In main.cpp, I call unsorted_5count_duplicates() and everything checks out. As soon as I pass the object to AssertCountCorrect(arr), I get the exact same issue each time:
main.cpp
TestSpace::ArrayData *arr = TestSpace::unsorted_5count_duplicates();
//During debug, I can check and see *arr has all values set correctly, including the array.
AssertSpace::AssertCountCorrect(arr);
AssertSpace.h
//snippet:
void AssertCountCorrect(struct TestSpace::ArrayData *arr) {
//I get -9.2559631349317831e+061 every time, for each value of arr->data.
// but, the memory reference is correct.
double *arrdata = arr->data;
for(int i = 0; i < arr->count; i++) {
std::cout << *(arrdata + i) << "\n";
}
}
I've tried passing by reference, making everything const, assigning data via pointers to the array... it all always yields the same result... everything checks out until I pass it to the AssertCountCorrect() function.
Solution I implemented
It was a simple, fundamental issue. I needed to copy all values of the array into the struct, as demonstrated below:
arr->data = (double *)calloc(5,sizeof(double));
for(int i = 0; i < 5; i++) {
*(arr->data + i) = *(data + i);
}
double data[] = { 3.5, 1.2, 1.2, 4.0, 3.5 };What do you expect this to do? This statement has no effect on thedatamember.