Thread: Help with 2D arrays in C
i'm not sure how make 2d array in c.
the code segfaults... i'm not pointers 'point' (no pun intended) me in right direction?code:#include <stdlib.h> void init_matrix(float*** matrix, int w, int h) { int x, y; float** tmpmatrix = (float**)malloc(sizeof(float*) * h); if( tmpmatrix == null ) { printf("couldn't allocate memory grid, got null pointer.\n"); exit(0); } for( y = 0; y < h; y++ ) { /* allocate row. */ float* row = (float*)malloc(sizeof(float) * w); if( row == null ) { printf("couldn't allocate memory row (%d), got null pointer.\n", y); exit(0); } for( x = 0; x < w; x++ ) { row[x] = (y * w) + x; } /* store row. */ printf("y = %d\n", y); tmpmatrix[y] = &row; } matrix = &tmpmatrix; } int main(int argc, char *argv[]) { /* initialize matrix. */ float** matrix; int w = 512, h = 512, x = 0, y = 0; init_matrix(&matrix, w, h); /* test matrix. */ for( y = 0; y < h; y++ ) { for( x = 0; x < w; x++ ) { printf("trying access %d,%d (y,x)\n", y, x); printf("answer=%d\n", matrix[y][x]); } } }
here simpler , easier understand method. note calloc fills newly created memory 0 there no need _init_ array.php code:#include <stdio.h>
#include <stdlib.h>
float **create_matrix(int w, int h)
{
int i;
float **matrix;
matrix = (float **)calloc(h, sizeof(float *));
if(matrix == null)
{
fprintf(stderr, "not enough memory!\n");
exit(1);
}
for(i = 0; i < h; i++)
{
matrix[i] = calloc(w, sizeof(float));
if(matrix[i] == null)
{
fprintf(stderr, "not enough memory!\n");
exit(1);
}
}
return matrix;
}
int main(int argc, char *argv[])
{
int i, j, h = 9, w = 7;
float **test = create_matrix(w, h);
for(i = 0; i < h; i++)
for(j = 0; j < w; j++)
fprintf(stdout, "matrix[%d][%d] = %f\n", i, j, test[i][j]);
return 0;
}
Forum The Ubuntu Forum Community Ubuntu Specialised Support Development & Programming Programming Talk Help with 2D arrays in C
Ubuntu
Comments
Post a Comment