I think this to be the easiest way. Very similar to double array[m][n] - but dynamicly allocated:
#include <stdio.h>
#include <stdlib.h>
void print(double *arr, int m, int n) // First transfer the number of the rows. Then the number of the columns.
{
int i, j;
for (i = 0; i < m; i++) { // Count the rows.
for (j = 0; j < n; j++) { // Count the columns.
// printf("%d ", *((arr+i*n) + j)); // Do not use this kind of writing: seems to work with integers.
// Please write the code as follows:
printf("%fd ", *((double *)arr+(i*n) + j)); // Herbert Schildt - published by Osborne page 103 :
// It is most important to declare the "base-type" of the values.
}
printf("\n");
}
}
void write_any_values_to_double_array(double *arr, int m, int n)
{
int i, j, count;
double any_value = 240.465;
for (i = 0; i < m; i++) { // Count the rows.
for (j = 0; j < n; j++) { // Count the columns.
*((double *)arr+(i*n) + j) = any_value;
any_value += 1.0;
}
}
} // end of function
int main()
{
//int arr[][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}};
// Problem: In C - in contrast to C++ - you have to define the size of one dimension of the array.
// Also when you transfer the array to a funktion. -> void function(double array[][5], ......);
int m = 4, n = 5; // Define the number of the rows first, then the number of the columns.
double* tri; // Create a pointer.
// Dynamically allocate memory using calloc()
tri = (double*)calloc((m) * n, sizeof(double)); // Then create some space for the values. Similar to: tri[m][n] Call free(tri); later!
// The function calloc() is similar to malloc().
// But all the elements are initiatized to 0.
print(tri, m, n);
write_any_values_to_double_array(tri, m, n);
print(tri, m, n);
*((double*)tri + (1 * n) + 3) = 3.14152864; // Secound row, 4. column
print(tri, m, n);
free(tri);
return 0;
}