Kitama
Kitama

Reputation: 31

Return 2d array and pass it as argument to another function

I'm new to C, I would like to ask a question about the use of functions in C.

I need to create two functions, the first one to create a 2D array and the second to print it. I use a file called matrices.c, a header called matrices.h and a main file.

The main file is the following:

 #include <stdio.h>
 #include <stdlib.h>
 #include "matrices.h"

int main() {
int m, n;
printf("Insert rows and colums of matrix A: ");
scanf("%d%d", &m,&n);
printf("Insert elements of the first matrix A\n");
int A[m][n];
A[m][n] = **create(m, n);
display(m, n, A[m][n]);

return 0;
}

The matrices.c file is:

#include "matrices.h"
#include <stdlib.h>
#include <stdio.h>

int **create(int m, int n){
    int  **A = (int **) malloc (sizeof(int *)*m);
    for (int i = 0; i < m; i++){
        A[i]=(int *)malloc(sizeof(int)*n);
        for (int j = 0; j < n; j++){
            printf("Element ");printf("%d", i+1);printf("%d", j+1);printf(":");
            scanf("%d",&A[i][j]);
        }
    }
    return A;
}


void display(int m, int n, int A[m][n]){
    for (size_t i = 0; i < m; i++){
        for (size_t j = 0; j < n; j++){
            printf("%d ", A[i][j]);
        }
        printf("\n");
    }
}

Finally the matrices.h file is the following:

#ifndef matrices_h
#define matrices_h
#include <stdio.h>

int **create(int m, int n);
void display(int m, int n, int A[m][n]);

#endif

The error that my compiler returns is related to the line

display(m, n, A[m][n]);

in the main file. It says: Thread 1: EXC_BAD_ACCESS (code=1, address=0x7ffe0000001a). Moreover, I have one more warning: Incompatible integer to pointer conversion passing 'int' to parameter of type 'int ( * )[ * ]' (in the same line).

I thank everyone that will be kind enough to help me :)

Upvotes: 0

Views: 37

Answers (1)

4386427
4386427

Reputation: 44274

You are not allocating a 2D array. What you create is a 1D array of pointers and then you make each of these point to a 1D array of int. Therefore you must change the code to use that "double int pointer" type all over.

Like:

int A[m][n];              --> int **A;
A[m][n] = **create(m, n); --> A = create(m, n);
display(m, n, A[m][n]);   --> display(m, n, A);

and

void display(int m, int n, int A[m][n]){ --> void display(int m, int n, int** A){

Upvotes: 1

Related Questions