I want to take in three arbitrary length buffers of doubles. Below is a short example
struct Data
{
double *foo[3];
};
int main(void)
{
double bar1[] = {1.0, 2.0, 3.0};
double bar2[] = {1.0, 2.0, 3.0, 4.0};
double bar3[] = {1.0, 2.0, 3.0, 4.0, 5.0};
struct Data *data = (struct Data*)malloc(sizeof(struct Data));
data->foo[0] = bar1;
data->foo[1] = bar2;
data->foo[2] = bar3;
printf("%lf %lf %lf\n", data->foo[0][0], data->foo[0][1], data->foo[0][2]);
printf("%lf %lf %lf %lf\n", data->foo[1][0], data->foo[1][1],
data->foo[1][2], data->foo[1][3]);
printf("%lf %lf %lf %lf %lf\n", data->foo[2][0], data->foo[2][1],
data->foo[2][2], data->foo[2][3], data->foo[2][4]);
return 0;
}
My concern is that if I malloc Data
in the manner above I run the risk of corrupt data. If I allocate memory on the heap for an array of pointers to double buffers (or essentially an arbitrarily sized two-dimensional array of doubles) without knowing the size, is the data protected in any way? I feel like it runs the possibility of overwritten data. Am I correct in this thinking? This compiles and prints, but I'm not sure I trust it in a much larger scale implementation.