評價: 0 回應: 0 閱覽: 131
置頂

動態配置下二維陣列參數傳遞

想嘗試練習指標與陣列的相關使用

compile時就宣告好大小的二維陣列依照置底方式傳遞應該沒問題

在動態配置的陣列傳遞時,想要採用轉成一維陣列卻無法得到正確結果

#include<stdio.h>


int c_array(int *a,int row,int column,int i,int j)
{
    printf("%d ",*( a + i*column +j ) );//使用pointer來控制矩陣
}


int main(void)
{
    int **ptr=NULL;
    int row,column;
    int i,j;

    while(1)
    {
        printf("row=\n");
        scanf("%d",&row);
        printf("column=\n");
        scanf("%d",&column);

        if(row==0 && column==0) break;

       ptr=(int**)malloc(sizeof(int*)*row);
       //生成一維指標陣列
       for(i=0;i<row;i++)
       {
           ptr[i]=(int*)malloc(sizeof(int)*column);
       }//二維

       for(i=0;i<row;i++)
       {
           for(j=0;j<column;j++)
           {
               ptr[i][j]=1;
           }
       }//將矩陣付值:1

       for(i=0;i<row;i++)
       {
           for(j=0;j<column;j++)
           {
               //printf("%d",ptr[i][j]);//測試用
               c_array((int*)ptr,row,column,i,j);//使用另外函數來print
           }

           printf("\n");//換行
       }

       for(i=0;i<row;i++) free(ptr[i]);
       free(ptr);//釋放記憶體

    }

    return 0;



}

 

會員登入 (先登入會員才能回覆留言喔!)

Facebook留言