简体   繁体   中英

2D array (pointer to pointer)

I want to fill 2D array with random numbers and then call it in main function and print it. But I can't access the function FillMatrix from main .

#define R 12 //row
#define S 10 //column

void FillMatrix(int m[][S], int row);
int main(int argc, char *argv[])
{
    int i, j;
    time_t t;

    // POINTER TO POINTER
    int **mat = (int **)malloc(R * sizeof(int *));
    if ((mat = (int**)malloc(R*sizeof(int))) == NULL)
    {
        printf("Error");
        return 0;
    }

    for (i = 0; i<R; i++)
        mat[i] = (int *)malloc(S * sizeof(int));

    FillMatrix(mat, R); //<- This line is the problem

    // RAND 0 - 1000
}

void FillMatrix(int m[][S], int row)
{
    int i, j;
    time_t t;
    srand((unsigned)time(&t));
    for (i = 0; i < row; i++)
        for (j = 0; j < S; j++)
            m[i][j] = rand() % 1000 + 0;
}

(mat = (int**)malloc(R*sizeof(int)) allocates the wrong amount of space; the type should be sizeof(int *) or equivalently sizeof *mat . Also you leak the memory you just allocated on the previous line.

To fix this, change if ((mat = (int**)malloc(R*sizeof(int))) == NULL) to if ( mat == NULL ) .


Also, int ** is not compatible with int[][S] . int ** represents an array where each line is a separate allocation, however int [][S] represents one contiguous memory block. You must choose which of those two approaches you want to use.

If you want to use the separate rows, then change the function to void FillMatrix(int **m, int row) (and it would be good style to have the number of columns as a parameter, instead of using the global S ).

Or if you want to use the contiguous memory block, change the allocation line to int (*mat)[S] = malloc(R * sizeof *mat);

Well, you're code is off a bit. I'm going to assume that your main function starts right before int i, j; and ends after the call to FillMatrix(mat, R); .

If that is the case then you need to either move your function definition of FillMatrix before you start your main function OR you need to forward declare your FillMatrix function before your main function.

The issue is that your main function cannot "see" your FillMatrix function. Order is VERY important. If something has not been declared, defined, or in some way shown to exist AT THE POINT IN QUESTION then it doesn't exist as far as the compiler is concerned. Think of it like trying to access some variable before you declare it in a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM