I am trying to run the following code but it gives me garbage data on accessing the struct array values. Why is this happening and how can I fix this? Once I move the malloc part to the main function it seems to work. But I want to keep the malloc in a separate function.
#include <cstdlib>
#include <limits>
#include <iostream>
using namespace std;
/*
*
*/
typedef struct{
float x;
float y;
} CoordinateData;
void tester(CoordinateData* cd_data){
cd_data = (CoordinateData*)malloc(5*sizeof(CoordinateData));
CoordinateData data = {41.2525,74.0744};
*cd_data = data;
}
int main(int argc, char** argv) {
CoordinateData* cd_data;
tester(cd_data);
std::cout << (*cd_data).x << "::" << (*cd_data).y << std::endl;
}
The output I get is 2.42126e-39::-1.51015e-05
The expected output is 41.2525::74.0744
Pass cd_data by address, not value:
Note also, the return value of
main()which you were missing. Also. this question is tagged as both C and C++. If it is the latter, usenewanddelete[]instead ofmallocandfree