0

I defined a function for initialising a 2D array through pointers and at the same time fell it with random values.

Then I print it and I don't see the expected values. Where is the bug in my code? I've been looking for hours.

#define MATRIX_SIZE 3

int **initialize_matrix(size_t m, size_t n){
    int i1,i2;

    int **ptr1=(int **)malloc(sizeof(int *)*m*n);
    int *ptr2=(int *)malloc(sizeof(int)*m);

    srand(time(0));
    for(i1=0;i1<MATRIX_SIZE;i1++){
        for(i2=0;i2<MATRIX_SIZE;i2++){
            ptr2[i2]=rand()%10;
            printf("%d ",ptr2[i2]);
        }
     }

    for(i1=0;i1<MATRIX_SIZE;i1++){
        ptr1[i1]=ptr2+m*i1;
    }
    printf("\nFinished generating\n");

    return ptr1;
}

void print_matrix(int** matrix_to_print){
    int i1,i2;

    for(i1=0;i1<MATRIX_SIZE;i1++)
    for(i2=0;i2<MATRIX_SIZE;i2++){
        printf("%d ",matrix_to_print[i1][i2]);
        if(i2==MATRIX_SIZE-1)
            printf("\n");
      }

}

This prints:

2 4 8
0 6 7 6 4 4 Finished generating Matriz 1: 6 4 4
135113 0 0 0 0 0

1
  • 1
    int **ptr1=(int **)malloc(sizeof(int *)*m*n);int *ptr2=(int *)malloc(sizeof(int)*m); : should be int **ptr1=(int **)malloc(sizeof(int *)*n);int *ptr2=(int *)malloc(sizeof(int)*m*n);. Why is MATRIX_SIZE used in the function initialize_matrix(size_t m, size_t n) ? Commented Dec 5, 2014 at 18:55

2 Answers 2

1

sample code

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MATRIX_SIZE 3

int **initialize_matrix(size_t m, size_t n){
//make dynamic 2D array like int a[m][n]
    int i1,i2;

    //There is no need to cast the return value of malloc in C
    int **ptr1=(int **)malloc(sizeof(int *)*m);

    srand(time(0));
    for(i1=0; i1<m; i1++){
        ptr1[i1] = (int*)malloc(sizeof(int)*n);
        for(i2=0; i2 < n; i2++){
            ptr1[i1][i2]=rand()%10;
            printf("%d ",ptr1[i1][i2]);
        }
     }
    printf("\nFinished generating\n");

    return ptr1;
}

void print_matrix(int** matrix_to_print, size_t m, size_t n){
    int i1,i2;

    for(i1=0;i1<m;i1++){
        for(i2=0; i2<n; i2++)
            printf("%d ", matrix_to_print[i1][i2]);
        printf("\n");
    }
}

int main(){
    int **p = initialize_matrix(MATRIX_SIZE, MATRIX_SIZE);
    print_matrix(p, MATRIX_SIZE, MATRIX_SIZE);
    {   //deallocate
        int i;
        for(i = 0; i < MATRIX_SIZE; ++i)
            free(p[i]);
        free(p);
    }

    return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

This solves my initial problem. I would like to ask one more thig though. If i call initalize_matrix(...) two times from main() to generate two different matrixes and then one third from operations on these two how can I do it? I can't freeright after calling initialize_matrix() so the 2 generated matrixes end up being the same...
@JoãoPereira int **p1 = initalize_matrix(...);int **p2 = initalize_matrix(...);int **p3 = initalize_matrix(...);, p3[x][y]=p1[x][y]+p2[x][y];...
0
//here is a possible code snippet to address your problem.
//it is commented as to what is being done.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// prototypes
void cleanUp( int **, int );
int **initialize_matrix( size_t, size_t );

int **initialize_matrix(size_t width, size_t height) // <-- use meaningful variable names
{
    int i; // outer loop index
    int j; // inner loop index

    // set initial array of pointers to integer
    int **my2dMatrix = calloc(height, sizeof(int*) ); // dont cast the returned value from malloc family
    if( NULL == my2dMatrix )
    { // then calloc failed
        perror( "calloc failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    // set pointer array to point to arrays of integers
    for( i=0; i<height; i++)
    {
        my2dMatrix[i] = malloc(sizeof(int)*width);
        if( NULL == my2dMatrix[i] )
        { // then malloc failed
            perror( "malloc failed" );
            cleanUp( my2dMatrix, height );
            exit( EXIT_FAILURE );
        }

        // implied else, malloc successful

    } // end for

    // fill array with random values
    srand(time(0));
    for(i=0; i<height; i++ )
    {
        for(j=0;j<width;j++)
        {
            my2dMatrix[i][j] = rand()%10;
            printf("%d ",my2dMatrix[i][j]);
        } // end for
    } // end for

    printf("\nFinished generating\n");

    return my2dMatrix;
} // end function: initialize_matrix

void cleanUp( int **my2dMatrix, int height )
{
    int i; // loop copunter
    for( i=0; i < height; i++ )
    {
        // free each row memory allocation
        free( my2dMatrix[i]); // ok to pass NULL to free,
                        // which is why initial pointer array created with calloc())
    }
    // free top level memory allocation
    free( my2dMatrix );
}

1 Comment

Minor: Questionable mixing use of int and size_t even though OP did it. Surely the compiler warned about for( i=0; i<height; i++). Suggest using size_t throughout. size_t i,j;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.