-3

I am trying to make some simple functions that does some operations on matrixes. But i can`t undestand why the following code is not working!. Can you please help me to understand what is wrong here and what should i do???

void create(int*** p, const int n)
{
    *p = (int**)calloc(n, sizeof(int));
    if(*p == NULL){
        printf("Error1");
    }

    int i;
    for(i = 0; i < n; i++){
        (*(p[i]) = (int*)calloc(n, sizeof(int)));

        if(*(p[i]) == NULL){
            printf("Error2");
        }
    }
}
void initializeMatrix(int*** p, const int n)
{
    int i, j;

    for(i = 0; i < n; i++){
        for(j = 0; j < n; j++){
            scanf("%d", &((p[i][j])));
        }
    }
}
void show(const int** p, const int n)
{
    int i, j;
    for(i = 0; i < n; i++){
        for(j = 0; j < n; j++){
            printf("%d ", ((p)[i][j]));
        }
        printf("\n");
    }
}
int main()
{
    int** p = NULL;

    create(&p, 2);
initializeMatrix(&p, 2);

    show(p, 2);

    return 0;
}
Rasuljon
  • 35
  • 2

1 Answers1

2

Problem 1

You are using *(p[i]) in create. it should be (*p)[i].

void create(int*** p, const int n)
{
    *p = (int**)calloc(n, sizeof(int));
    if(*p == NULL){
        printf("Error1");
    }

    int i;
    for(i = 0; i < n; i++){

        // FIXED 
        (*p)[i] = (int*)calloc(n, sizeof(int)));

        // FIXED
        if( (*p)[i] == NULL){
            printf("Error2");
        }
    }
}

Problem 2

You are passing the wrong size to first calloc in the function. You need to use sizeof(int*). After all, you want the returned value to be a pointer to n pointers to int, not a pointer to n objects of type int.

This is a critical error that leads to undefined behavior unless sizeof(int) is the same as sizeof(int*) on your platform.

Change the line to

    *p = (int**)calloc(n, sizeof(int*));

More importantly, you can make that function a bit easier by returning a pointer. It will be easier to write such a function.

int** create(int n)
    int **p = calloc(n, sizeof(*p));
    if(p == NULL){
        printf("Error1");
    }

    int i;
    for(i = 0; i < n; i++){

        p[i] = calloc(n, sizeof(*p[i])));

        if( p[i] == NULL){
            printf("Error2");
        }
    }

    return p;
}

and use it as:

int** p = create(2);
R Sahu
  • 204,454
  • 14
  • 159
  • 270