簡體   English   中英

在 C 中的函數中傳遞數組

[英]Passing Arrays in functions in C

我有這段代碼,它模擬 Conway 的游戲(對於這個問題並不重要),我只是想知道如何將我的數組,板,傳遞給我的函數鄰居。 我一直收到一個編譯器錯誤,說我在函數聲明中有一個不完整的元素類型,即使我被告知我需要將空方括號放在那里來傳遞函數,並且沒有方括號它不起作用。 如果有人可以在這里幫助傳遞該功能,那將非常有幫助。 這是我的代碼:

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

struct info
{
    int red;
    int blue;
};

struct info neighbor(char board[][], int, int);

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        printf("usage: dimensions repititions\n");
        return 1;
    }
    srand(time(NULL));
    int games = 0;
    int d = atoi(argv[0]);
    int repititions = atoi(argv[1]);
    //create board
    char board [d][d];
    for(int i = 0; i < d; i++)
    {
        for(int j = 0; j < d; j++)
        {
            int choice = rand() % 100;
            if(choice < 44)
            {
                if(choice % 2 == 0)
                {
                    board[i][j] = '#';
                }
                else
                {
                    board[i][j] = '*';
                }
            }
            else
            {
                board[i][j] = '.';
            }
        }
    }
    while(games < repititions)
    {
        for(int i = 0; i < d; i++)
        {
            for(int j = 0; j < d; j++)
            {
                neighbor(board, i, j);
            }
        }
    }

}

struct info neighbor(char board, int i, int j)
{
    char grid [3][3];
    for(int u = 0; u < 3; u++)
    {
        for(int v = 0; v < 3; v++)
        {
            grid[u][v] = board[i][j];
            i ++;
        }
        j++;
    }
}

將多維數組傳遞給函數時,必須指定除第一個維度之外的所有維度的大小。 當此類數組為可變長度時,聲明應如下所示:

struct info neighbor(int, int, char board[*][*]);

定義如下所示:

struct info neighbor(int i, int j, char board[i][j]) {

在這種情況下,您需要在初始化二維數組的函數參數中傳遞列數。

struct info neighbor(char board[][number_of_columns], int, int);

struct info neighbor(char board[][number_of_columns], int i, int j)

暫無
暫無

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

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