簡體   English   中英

如何將指針傳遞給 function 並在那里創建一個以指針作為起始地址的矩陣?

[英]how to pass a pointer to a function and create a matrix there with the pointer as the starting address?

應該打印相同的矩陣,但在 function 之外它不打印矩陣的任何值。 這里有什么問題?(我不希望 function 中的參數名稱和傳遞的變量名稱相同。)

0.000000 0.000000 0.000000 0.000000 0.000000
1.000000 1.000000 1.000000 1.000000 1.000000
2.000000 2.000000 2.000000 2.000000 2.000000
3.000000 3.000000 3.000000 3.000000 3.000000

0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 0.000000

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

void tryn(double *a)
{
    int i,j;
    a=(double *)calloc(20,sizeof(double));
    for(i=0;i<4;i++)
    {
        for(j=0;j<5;j++)
        {
            *(a+i*5+j)=i;
        }
    }

    for(i=0;i<4;i++)
    {
        for(j=0;j<5;j++)
        {
            printf("%lf ",*(a+i*5+j));
        }
        printf("\n");
    }


}
int main()
{
    int i,j;
    double *arr;
    tryn(arr);
    for(i=0;i<4;i++)
    {
        for(j=0;j<5;j++)
        {
            printf("%lf ",(arr+i*5+j));
        }
        printf("\n");
    }
    free(arr);
}

output 它的捐贈

C 中的函數參數是按值傳遞的。 這意味着對tryna的更改不會反映在調用 function 中,因此main中的arr保持未初始化。

您需要將arr的地址傳遞給您的 function:

tryn(&arr);

並相應地更改 function 中的參數類型:

void tryn(double **arr)
{
    double *a=calloc(20,sizeof(double));
    ...
    *arr = a;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM