在 C 中创建数组并将指向所述数组的指针传递给函数

标签 c arrays function pointers

<分区>

我已经阅读了几篇与我关于 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);

接下来,当您在 main 中声明您的 arrays 数组时,您需要更具体地说明维度 - 类似于函数的参数列表:

char arrays[x][NUM_Y];

选择 NUM_Y 使其足够大以适应您期望的数据量。

接下来,您没有在 main 中初始化 xy,然后继续使用这些变量声明一个数组。这很糟糕,因为这些变量可以包含任何垃圾值,包括 0,因此您最终会得到一个具有意外维度/大小的数组。

最后,当你将数组传递给你的函数时,不要取消引用它,只传递变量:

readFile(arrays, x, y);

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

关于在 C 中创建数组并将指向所述数组的指针传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11713157/

相关文章:

c - C 中全局结构变量的最佳使用

c - 将 CSV 文本文件中的值输入到数组中

python - 使用 numpy 切片数组索引 numpy 数组

javascript - 在 Javascript 中执行作为参数传递的函数?

c - 在c中通过方法/函数传递结构的问题

c - 使用 C 传递/使用终端参数

c - 通过 snprintf 在 C 中填充静态字符串缓冲区

c++ - 为数组中的所有元素分配相同值的方法

c++ - 缓冲波形文件/样本管理

c++ - 如何结束文件输出它的数据?