简体   繁体   English

返回动态分配的二维数组的问题

[英]Problem with returning dynamically allocated 2d array

When I print the 2D array inside the function, it gives me the desired output but when I return the array and try to print it in main, it gives no output. 当我在函数内部打印2D数组时,它给了我想要的输出,但是当我返回数组并尝试在main中打印它时,它没有输出。

int** getPascal(int size)
{

    int i,j;
    int **pTri = (int **)malloc(size * sizeof(int *));
    for(i = 0 ; i < size ; i++)
    {
        pTri[i] = (int *)malloc((i+1) * sizeof(int));
        j++;
    }

    pTri[0][0] = 1;
    for(i = 1 ; i < size ; i++)
    {
        pTri[i][0] = 1;
        for(j = 1; j < i; j++)
        {
            pTri[i][j] = pTri[i-1][j-1] + pTri[i-1][j];
        }
        pTri[i][i] = 1;
    }
    // pTri prints properly here
    return pTri;
}

int main()
{

    int size;
    scanf("%d",&size);

    int **pascalTriangle = getPascal(size);
    // printing pascalTriangle gives no output.
    return 0;
}

Can you show your print function? 可以显示print功能吗? Mine prints the correct values in both sections of the code. 我的在代码的两个部分中打印正确的值。 Try using it: 尝试使用它:

void printFunc(int **pascalArray, int size)
{
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < (i+1); j++)
        {
            printf("%d", pascalArray[i][j]);
        }
        printf("\n");
    }
}

I tried with size = 5 and I get in both places: 我尝试使用size = 5并且在两个地方都得到了:

1 1个
11 11
121 121
1331 1331
14641 14641
1 1个
11 11
121 121
1331 1331
14641 14641

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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