So I'm trying to dynamically malloc memory in other function. Here is my simplified code, I couldn't get it right.
The first malloc initialized memory.
The second malloc (realloc) expand it, my original code use it in a loop, so the memory can keep expanding.
I got the following result:
size=2
data=0.000000
data=2.500000
But I'm expecting
size=2
data=1.500000
data=2.500000
Any Suggestions? Here is my code.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
time_t time_stamp;
double data;
} sensor_data;
void Get_Data(sensor_data **raw_data,int *size){
(*size) = 0;
*raw_data = (sensor_data *)malloc(sizeof(sensor_data) * ((*size) + 1));
(*raw_data)[(*size)].data = 1.5;
(*size)++;
*raw_data = (sensor_data *)malloc(sizeof(sensor_data) * ((*size) + 1));
(*raw_data)[(*size)].data = 2.5;
(*size)++;
}
int main() {
sensor_data *raw_data;
int size = 0;
Get_Data(&raw_data,&size);
printf("size=%d\n",size);
int i = 0;
for( i = 0; i < size; i++)
{
printf("data=%f\n",raw_data[i].data);
}
free(raw_data);
return 0;
}