Skip to main content

Thread: Help with 2D arrays in C


i'm not sure how make 2d array in c.

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]);  		}  	}  }
the code segfaults... i'm not pointers 'point' (no pun intended) me in right direction?

php code:
#include <stdio.h>
#include <stdlib.h>

float **create_matrix(int wint h)
{
    
int i;
    
float **matrix;
    
    
matrix = (float **)calloc(hsizeof(float *));
    if(
matrix == null)
    {
        
fprintf(stderr"not enough memory!\n");
        exit(
1);
    }
    
    for(
0hi++)
    {
        
matrix[i] = calloc(wsizeof(float));
        if(
matrix[i] == null)
        {
            
fprintf(stderr"not enough memory!\n");
            exit(
1);
        }
    }
    
    return 
matrix;
}

int main(int argcchar *argv[])
{
    
int ij97;
    
float **test create_matrix(wh);

    for(
0hi++)
        for(
0wj++)
            
fprintf(stdout"matrix[%d][%d] = %f\n"ijtest[i][j]);

    return 
0;

here simpler , easier understand method. note calloc fills newly created memory 0 there no need _init_ array.


Forum The Ubuntu Forum Community Ubuntu Specialised Support Development & Programming Programming Talk Help with 2D arrays in C


Ubuntu

Comments

Popular posts from this blog

Thread: PKI Client 5.00 install (for eToken Pro)

ATmega2560-Arduino Pin Mapping

Crossfader Arduino Tutorial