在C中创建数组并将指向该数组的指针传递给函数[重复]

2024-02-02

我读过几篇与我的 C 问题相关的帖子。这确实帮助我减少了错误。但是,我仍然遇到其他帖子无法为我解决的问题。基本上,这就是我正在尝试做的事情。

在 main 中定义一个数组。我将指向该数组的指针传递给函数。该函数将打开一个文件,解析该文件,并将该文件中的信息放入我传入的指针的数组中。好吧,它失败了。

我得到的错误是:

work.c:12: error: array type has incomplete element type
work.c: In function ‘main’:
work.c:20: error: type of formal parameter 1 is incomplete
work.c: At top level:
work.c:25: error: array type has incomplete element type

整个代码如下。但我认为你只需要关注我如何定义数组、指针等。

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

//Defining Preprocessed Functions 
char readFile(char array[][], int, int);
//void displayStudentInfo(int*);

//Implements Step 1 and 2 of Student Instuctions
int main(int argc, char* argv[])
{
    int x = 256;
    int y = 256;
    char arrays[x][y]; 
    readFile(&arrays,x,y);
    //displayStudentInfo(&array);
    return 0;
}

char readFile(char array[][], int x, int y)
{
    char line[256]; //Three columns 0, 1, 2 corresponds to firstname, lastname, score. 
    char* string;
    int columns = 3;

    x = 0;
    //int y; //Defines rows and columns of 2D array to store data
    //char array[x][y]; //Defines the array which stores firstname, lastname, and score



    FILE *file;
    file = fopen("input.txt", "r");

    //Test to make sure file can open 

    if(file  == NULL)
    {
        printf("Error: Cannot open file.\n");
        exit(1);
    }
    else
    {
        while(!feof(file))
        {
          /* 
            if(fgets(line, 256, file))//fgets read up to num-1 characters from stream and stores them in line
            {
                printf("%s", line);
            }
            */
            if(fgets(line,256,file)!=NULL)
            {
                for(y = 0; y < columns; y++)
                {
                    array[x][y]=strtok(fgets(line,256,file), " ");
                }
                x++;
            } 
        }
    }
    fclose(file);
}

你有一些问题。前两个是相似的:

首先,您在函数声明中使用无界数组:编译器需要了解有关参数的更多信息,即维度。在这种情况下,提供以下维度之一就足够了:

char readFile(char array[][NUM_Y], int, int);

现在编译器有足够的信息来处理该数组。您可以省略这样的维度,但通常最好是明确的,并将函数声明为:

char readFile(char array[NUM_X][NUM_Y], int, int);

接下来,当你宣布你的arraysmain 中的数组,您需要更具体地了解维度 - 类似于函数的参数列表:

char arrays[x][NUM_Y];

Choose NUM_Y足够大以适合您期望的数据量。

接下来,您没有初始化x and y in main,然后继续使用这些变量声明一个数组。这很糟糕,因为这些变量可能包含任何垃圾值,包括0,所以你最终会得到一个意想不到的尺寸/大小的数组。

最后,当您将数组传递给函数时,不要取消引用它,只需传递变量即可:

readFile(arrays, x, y);

在 C 中,当您将数组传递给函数时,实际传递的是指向第一个元素的指针。这意味着该数组未被复制,因此该函数可以访问它期望更改的内存区域。我猜你正在取消引用,因为这是你学会传递要在函数中更改的更简单类型的方式,例如ints or structs,但对于数组,您不需要这样做。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在C中创建数组并将指向该数组的指针传递给函数[重复] 的相关文章

随机推荐