簡體   English   中英

使用指針方法打印二維動態分配的數組

[英]Printing 2d dynamically allocated array using pointer to pointer method

在此代碼中,我試圖將 memory 動態分配給二維數組並打印它我在這里面臨的問題是我無法正確獲取 output 假設我的輸入是大小為 2*2 [1,2,3, 4] 但打印的 output 是 [1,1,1,1]。

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

int output_func(int row, int col, int *ptr)
{
    printf("\nThis is your first matrix: \n\n");
    for (int i = 0; i < row; i++)
    {
        printf("\t  |");
        for (int j = 0; j < col; j++)
        {
            printf(" %d ", *ptr);
        }
        printf("|\n");
    }
}

int main()
{
    int **ptr;
    int row, col;
    int i, j;

    printf("enter the no of rows for the matrix: ");
    scanf("%d", &row);
    printf("enter the no of col for the matrix: ");
    scanf("%d", &col);

    ptr = (int **)malloc(row * sizeof(int *));
    for (int i = 0; i < row; i++)
    {
        ptr[i] = (int *)malloc(col * sizeof(int));
    }

    // input of first matrix
    printf("\nEnter the elements for first matrix :\n");
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            printf("\t A[%d,%d] = ", i, j);
            scanf("%d", &ptr[i][j]);
        }
    }

    output_func(row, col, *ptr);
    return 0;
}

如果您希望 function 打印使用指向 int 的 arrays 的指針數組(也稱為鋸齒狀數組)分配的數組,則必須將指針傳遞給指針數組。

換句話說 - 這是錯誤的:

int output_func(int row, int col, int *ptr)
                                  ^^^^^^^^
                                  A int-pointer but you want
                                  a pointer to a pointer to int
                                  which is "int **ptr"

也一樣

int output_func(int row, int col, int **ptr)
{
    printf("\nThis is your first matrix: \n\n");
    for (int i = 0; i < row; i++)
    {
        printf("\t  |");
        for (int j = 0; j < col; j++)
        {
            printf(" %d ", ptr[i][j]);
        }
        printf("|\n");
    }
}

並稱之為:

output_func(row, col, ptr);
#include <stdio.h> #include <stdlib.h> // int* ptr -> int** ptr void output_func(int row, int col, int** ptr) { printf("\nThis is your first matrix: \n\n"); for (int i = 0; i < row; i++) { printf("\t |"); for (int j = 0; j < col; j++) { // *ptr -> ptr[i][j] printf(" %d ", ptr[i][j]); } printf("|\n"); } } int main() { int** ptr; int row, col; printf("enter the no of rows for the matrix: "); scanf("%d", &row); printf("enter the no of col for the matrix: "); scanf("%d", &col); ptr = (int**)malloc(row * sizeof(int*)); for (int i = 0; i < row; i++) { ptr[i] = (int*)malloc(col * sizeof(int)); } // input of first matrix printf("\nEnter the elements for first matrix :\n"); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { printf("\t A[%d,%d] = ", i, j); scanf("%d", &ptr[i][j]); } } output_func(row, col, ptr); return 0; }

暫無
暫無

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

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