I have created a 2 d array which reads as follows
int i,j,lx,ly;// lx,ly are the row and column respectively
double** a;
a=(double**) malloc(
This code allocates a 10 by 5 contiguous block of memory, initializes it with incrementing doubles, and then prints the values indexed by x and y:
#include "2d.h"
int main(void){
unsigned int x,y;
const unsigned int width = 10;
const unsigned int height = 5;
//we need an index into the x of the array
double * index[width];
//need the memory to store the doubles
unsigned int memorySizeInDoubles = width * height;
double * memory = malloc(memorySizeInDoubles * sizeof(double));
//initialize the memory with incrementing values
for(x = 0; x < memorySizeInDoubles; ++x){
memory[x] = (double) x;
}
//initialize the index into the memory
for(x = 0; x < width; ++x){
index[x] = memory + height * x;
}
//print out how we did
for(x = 0; x < width; ++x){
for(y = 0; y < height; ++y){
printf("[%u, %u]: Value = %f\n", x, y, index[x][y]);
}
}
free(memory);
return 0;
}
The 2d.h file should contain these lines:
#include
#include
int main(void);
Note: The memory created is only contiguous for some definitions. The memory is logically contiguous, but not necessarily physically contiguous. If this memory is for a device driver for instance, malloc won't work.