Reputation: 2527
In C, I am trying to declare a 2D array outside of any function so that it can be shared by the functions. I know in the single dimensional case you can do the following(and make it behave LIKE an array):-
#include<stdlib.h>
#include<stdio.h>
int *ptr;
int main(){
int n=5;
int i;
ptr = malloc(n*sizeof(*ptr));
for(i=0; i<n; i++){
ptr[i] = i;
printf("%i\n", ptr[i]);
}
free(ptr);
return 0;
}
I am wondering how this would work for the multidimensional case.
Upvotes: 0
Views: 133
Reputation: 5208
In stead of a single pointer, you just use a double pointer:
#include<stdlib.h>
#include<stdio.h>
int **ptr;
int main() {
int n = 5;
int m = 10;
int i, j;
ptr = malloc(n * sizeof(int*));
for(i=0; i<n; i++) {
ptr[i] = malloc(m * sizeof(int));
for(j=0; j<m; j++) {
ptr[i][j] = j;
printf("%i\n", ptr[i][j]);
}
}
for(i=0; i<n; i++) {
free(ptr[i]);
}
free(ptr);
return 0;
}
Things you should be wary of:
Upvotes: 1
Reputation: 78903
As long as you fix the second dimension you can basically use the same "trick":
double (*A)[42];
If the second dimension is to be dynamic, too, you'd have to declare it in function scope:
double (*B)[n];
as a pointer to VLA, variable length array, and then pass the pointer to array to functions as
void f(size_t m, double (*aB)[m]);
you'd allocate such a 2D array in one go
B = malloc(sizeof(double[m][n]));
and thus you ensure that your matrix is contiguously allocated.
Upvotes: 0
Reputation: 133557
If you want to access it using two indices with []
operator then you will need to use a pointer to pointer to int
and allocate each single inner 1D array:
int **ptr = malloc(R*sizeof(int*));
for (int i = 0, i < R; ++i)
ptr[i] = malloc(C*sizeof(int));
ptr[i][j] = 40;
But you can also directly create a single 1D array of R*C
elements and then access it by calculating the correct index ptr[R*i + j]
or ptr[C*j + i]
.
Upvotes: 0