簡體   English   中英

如何通過添加指針來修復我的 C 代碼?

[英]How can I fix my C code by adding pointers?

我在下面添加了我的代碼。 我創建了一個 5x5 單位矩陣,但我的老師希望我們使用指針/尋址方法來顯示矩陣。 我不完全理解指針,並且在將它添加到我的代碼中遇到了麻煩。 我了解如何創建矩陣,但不了解如何使用指針。 任何幫助將不勝感激。

    #include<stdio.h>

int main() {

   int i;
   int j;
   int ar[i][j];//initialize the array
   int ptr;
    *ptr = ar;
   for(i = 0; i < 5; i++){
       for( j=0; j<5; j++) {

          //if i = j, the array will = 1 
         if (i == j ){          
           ar[i][j] = 1;
           printf("%d",ar[i][j]);
        } 

        //else it will equal 0
        else {
        ar[i][j] = 0;
        printf("%d",ar[i][j]);
     }
       }
   }
}

如何通過添加指針來修復我的 C 代碼?

減去您對Identity的函數調用的拼寫錯誤,您的代碼實際上並未損壞,因此“添加指針”並不能解決任何問題。

我了解如何創建矩陣,但不了解如何使用指針。

你這么說,但你實際上並沒有用發布的代碼創建一個矩陣; 您只是打印出類似於單位矩陣的模式。

..我的老師希望我們使用指針/尋址方法來顯示矩陣。 我不完全理解指針,而且我在將它添加到我的代碼中遇到了麻煩。

如果您的老師希望您使用指針來顯示矩陣,那么您必須實際創建一個。 這可以靜態或動態地完成。 對於初學者/學生來說,靜態最有意義。 你會這樣做: int matrix[5][5]

理解指針通常是 C 新手最難掌握的方面之一,所以這是正常的。 之前可能已經對您說過,但我再說一遍:指針指向內存位置。 您可以使用該指針來獲取內存位置中的值(又名解引用)。

例如:

int a = 10;
int * p = &a; //p points to the memory location where a is stored

/* these print the same thing */
printf("%d\n", a);
printf("%d\n", *p); //dereferencing

這與數組和矩陣有什么關系? 聲明數組時,該數組的名稱是指數組開頭的內存位置。 每個連續元素都位於距開頭的某個偏移處,這意味着第 n 個元素位於起始地址加 (n - 1) 處。 這是靜態分配數組並分配該數組的各個內存位置的示例:

int a[10] = {0}; //an array of 10 signed integers that have been initialized to 0
printf("0x%x\n", a); //prints the beginning address of the array a

a[0] = 10; //assign the 0th element
printf("%d\n", a[0]); //prints 10

*a = 11; //this also assigns the 0th element
printf("%d\n", *a); //prints 11

a[1] = 12; //assign the 1st element
printf("%d\n", a[1]); //prints 12

*(a + 1) = 13; //this also assigns the 1st element
printf("%d\n", *(a + 1)); //prints 13

矩陣是一個數組數組,但所有元素在內存中彼此相鄰,因此您可以以線性方式尋址元素:beginning_address + current_row * total_number_of_columns + current_column

知道了這一點,讓我們改變你的Identity函數:

int Identity(int * ptr, int num) { 
    int row, col; 

    for (row = 0; row < num; row++) { 
        for (col = 0; col < num; col++) { 
            // Check if row is equal to column  
            if (row == col) 
                *(ptr + row*num + col) = 1;
            else
                *(ptr + row*num + col) = 0; 
        }  
    } 
    return 0; 
}

現在它需要一個指向 int 的指針和單位矩陣的大小。 要使用它,我們將向它傳遞一個指向矩陣開頭的指針以及矩陣的大小。

像這樣:

int main(){

    /* this needs to match your matrix dimensions!! */
    int size = 5; 

    /* statically allocate 5 x 5 matrix of signed integers */
    int matrix[5][5] = {0};

    /* modifies our matrix to make it an identity matrix */
    Identity(&matrix[0][0], size); //first argument is the address of the element located in row 0, column 0

    /* now go through and print elements of the matrix */
    //I'm going to leave this part up to you

    return 0;

}

有關 C 中矩陣的更多信息,請查看本 教程

#include <stdio.h>

int main(void) {
  // const
  int ROWS= 3,  COLS= 4;

  // variable
  int row, col;

  // 2d array
  int arr[ROWS][COLS];

  // fill pointer with first address of array
  int *ptr = &arr[0][0];

  // print the element of the array via pointer ptr
  for (row = 0; row < ROWS; row++) {
    for (col = 0; col < COLS; col++) {
      if(row == col) {
         *(ptr + (row*COLS + col)) = 1;
      }
      else {
         *(ptr + (row*COLS + col)) = 0;
      }
      printf("%d ", *(ptr + (row*COLS + col)));
    }
    printf("\n");
  }   
  return 0;
}

輸出:

1 0 0 0                                                                                                                                
0 1 0 0                                                                                                                                
0 0 1 0 

任何數組在傳遞給函數時都會衰減為指針。 通過傳遞合適的“大小”信息,您可以將其用作矩陣。

所以你所需要的只是下面的代碼 - 這將傳遞a作為指向int 數組(大小為 n)的指針 然后您可以使用簡單的數組索引取消引用指針:

#include <stdio.h>

void make_identity(int n, int a[n][n])
{
    for (int i = 0; i < n; ++i)
    {
        for (int j=0; j < n; ++j)
        {
            if (i==j)
                a[i][j]=1;
            else
                a[i][j]=0;
        }
    }
}

void print_matrix(int n, int a[n][n])
{
    for (int i = 0; i < n; ++i)
    {
        for (int j=0; j < n; ++j)
        {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }
}

int main(void) {
    int size = 5;   // Just change size to get another matrix size
    int matrix[size][size];
    make_identity(size, matrix);
    print_matrix(size, matrix);
    return 0;
}

輸出:

1 0 0 0 0 
0 1 0 0 0 
0 0 1 0 0 
0 0 0 1 0 
0 0 0 0 1 

編寫代碼的另一種方法是:

void make_identity(int n, int (*a)[n])
{
     ...
}


void print_matrix(int n, int (*a)[n])
{
     ...
}

它會給你完全相同的結果(雖然可讀性較差,IMO)。

在這兩種情況下, a都是指向int 數組(大小為 n)的指針

暫無
暫無

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

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