Create 2D array by passing pointer to function in c

后端 未结 3 1204
情书的邮戳
情书的邮戳 2021-01-20 04:55

So I read dozens of examples of passing an 2D array pointer to function to get/change values of that array in function. But is it possible to create (allocate memory) inside

3条回答
  •  灰色年华
    2021-01-20 05:12

    Yes, passing a pointer to int ** (but 3 stars is considered bad style), I suggest to return an allocated variable from your function:

    int **createArr(int x, int y)
    {
        int **arrPtr;
        int i, j;       //Loop indexes
    
        arrPtr = malloc(x*sizeof(int*));
        if (arrPtr == NULL) { /* always check the return of malloc */
            perror("malloc");
            exit(EXIT_FAILURE);
        }
        for (i = 0; i < x; ++i) {
            arrPtr[i] = malloc(y*sizeof(int));
            if (arrPtr[i] == NULL) {
                perror("malloc");
                exit(EXIT_FAILURE);
            }
        }
        for (i = 0; i < x; ++i) {
            for (j = 0; j < y; ++j) {
                arrPtr[i][j] = i + j;
            }
        }
        return arrPtr;   
    }
    

    Call it using:

    arr = createArr(x, y);
    

提交回复
热议问题