簡體   English   中英

C語言生成矩陣

[英]Generating matrix in C language

我無法解決簡單的任務來生成給定大小的矩陣。 我遇到了太多不明白的錯誤,例如:C2087、C2131 或 C2447(Microsoft Visual Studio)如果可以請幫助我

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iomanip>
int max = 100;



void random(int & size, int M[][])
{   for (int i = 0; i < size; i++)
    {   for (int j = 0; j < size; j++)
        {
            M[i][j] = rand() % 9;
        }
    }
}

void display(int size, int M[][])
{   for (int i = 0; i < size; i++)
    {   for (int j = 0; j < size; j++)
        {
            printf("%d", &M[i][j]);
        }
    }
}

int main()
{
    printf("give me matrix size\n");
    int size;
    scanf_s("%d", &size);
    //int* M = new int[size][size];
    int M[max][max];

    random(size, M);
    display(size, M);

    return 0;
}

在 c 中處理數組的方式存在問題。 數組實際上並不是作為數組傳遞,而是作為指針傳遞。

考慮這個例子

void print_arr (int array[], int length);
void print_arr (int * array, int length);
void print_arr (int array[10], int length);
void print_arr (int array[11], int length);

這四個函數,就c而言,是相同的。 當您將數組作為函數參數傳遞時,您實際上只是傳遞了一個指針。 它可以正常工作,因為您可以訪問指針的索引。 當你寫

int function (int array[]) {
   return array[3]; 
}

C 將獲取數組的地址,添加(3 * sizeof(int))並返回該值。 它可以這樣做,因為它知道數組的每個元素的大小都是int

這樣做的問題是您不能在 c 中傳遞二維數組。 當你寫

void function (int array[][]) {
    array[2][3];
}

C 將首先計算第一個索引。 問題是它不知道偏移數組的大小。 如果您的陣列是 4 x 4 怎么辦? 如果是 7 乘 9 怎么辦? 每個可能的大小都需要不同的偏移量,而 c 不知道是哪個。

有幾個選項。 要么提前寫好尺寸,像這樣:

int function (int array[10][10]) {
    return array[2][3];
}

這告訴 c 數組的大小,並讓它正確計算偏移量。

或者,如果您不提前知道大小,請手動傳遞信息,如下所示:

int function (int * array, int width) {
    int index = (2 * width) + 3;
    return array[index];
}

在此示例中,您基本上是在手動執行 c 通常為您執行的數學運算。

謝謝卡森。 所以我試圖通過制作長數組來制作矩陣。 我仍然對我認為的指針有問題。

我的錯誤:Error C2540 non-constant expression as array bound line 30

錯誤 C2440 'initializing':無法從 'int (*)[1]' 轉換為 'int *' 第 30 行

錯誤 C2664 'void random(int,int *)':無法將參數 2 從 'int' 轉換為 'int *' 第 32 行

錯誤 C2664 'void wypisz(int,int *)': 無法將參數 2 從 'int' 轉換為 'int *' 第 33 行

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

void random(int size, int * M)
{

    for (int i = 0; i < size^2; i++)
    {
            int x = rand() % 9;
            M[i] = x;
    }
}

void display(int size, int *M)
{
    for (int i = 0; i < size^2; i++)
    {
        printf("%d ", &M[i]);
        if(size%i==0)
        printf("\n");
    }
}

int main()
{
    printf("Gimme size: \n");
    int size;
    scanf_s("%d", &size);
    int* M = new int[size][size];

    random(size, *M);
    display(size, *M);

    return 0;
}

暫無
暫無

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

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