Write a C function to allocate memory to a 2d array dynamically.
int** foo(int rows,int columns){
int **a;
a = (int **)malloc(rows*sizeof((int *));
for(int i = 0;i<rows;i++)
a[i] = (int *)malloc((columns)*(sizeof(int));
return a;
}
Method 2:
#define oops(s) { perror((s)); exit(EXIT_FAILURE); }
#define MALLOC(s,t) if(((s) = malloc(t)) == NULL) { oops("error: malloc() "); }
#define INCREMENT 10
double **xyz;
int i;
MALLOC(xyz, sizeof(double *) * INCREMENT);
for (i = 0; i < INCREMENT; i++) {
MALLOC(xyz[i], sizeof(double) * 3);
}
Our double pointer, xyz is our actual storage 2D array. We must use a double pointer, because we are pointing to multiple pointers of doubles! If this sounds confusing, think of it this way. Instead of each array entry having a real double entry, each array position contains a pointer to another array of doubles! Therefore, we have our desired 2D array structure.
The first MALLOC call instructs malloc to create 10 double pointers in the xyz array. So each of these 10 array positions now has an unitializied pointer to data of type pointer to a double. The for loop goes through each array position and creates a new array at each position to three doubles, because we want to read in x, y, z coordinates for each entry. The total space we just allocated is 10 spaces of 3 doubles each. So we've just allocated 30 double spaces.
Useful Links:
http://randu.org/tutorials/c/dynamic.php
http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_3.html
int** foo(int rows,int columns){
int **a;
a = (int **)malloc(rows*sizeof((int *));
for(int i = 0;i<rows;i++)
a[i] = (int *)malloc((columns)*(sizeof(int));
return a;
}
Method 2:
#define oops(s) { perror((s)); exit(EXIT_FAILURE); }
#define MALLOC(s,t) if(((s) = malloc(t)) == NULL) { oops("error: malloc() "); }
#define INCREMENT 10
double **xyz;
int i;
MALLOC(xyz, sizeof(double *) * INCREMENT);
for (i = 0; i < INCREMENT; i++) {
MALLOC(xyz[i], sizeof(double) * 3);
}
Our double pointer, xyz is our actual storage 2D array. We must use a double pointer, because we are pointing to multiple pointers of doubles! If this sounds confusing, think of it this way. Instead of each array entry having a real double entry, each array position contains a pointer to another array of doubles! Therefore, we have our desired 2D array structure.
The first MALLOC call instructs malloc to create 10 double pointers in the xyz array. So each of these 10 array positions now has an unitializied pointer to data of type pointer to a double. The for loop goes through each array position and creates a new array at each position to three doubles, because we want to read in x, y, z coordinates for each entry. The total space we just allocated is 10 spaces of 3 doubles each. So we've just allocated 30 double spaces.
Useful Links:
http://randu.org/tutorials/c/dynamic.php
http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_3.html
http://c-faq.com/~scs/cclass/int/sx9b.html
ReplyDelete