在C中创建数组并将指针传递给所述数组以起作用

时间:2012-07-29 21:36:25

标签: 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);
}

3 个答案:

答案 0 :(得分:3)

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

首先,你在函数声明中使用了一个无界数组:编译器需要更多地了解参数,即维度。在这种情况下,提供其中一个维度就足够了:

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,使其足够大,以适应您期望的数据量。

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

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

readFile(arrays, x, y);

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

答案 1 :(得分:2)

char arrays[x][y];:x,y必须是常量或实际值,而不是变量:http://www.acm.uiuc.edu/webmonkeys/book/c_guide/1.2.html#arrays

您可以通过声明指针来解决此限制,并将其分配给在malloc保留的每个位置使用malloc(sizeof(byte)* y)x次保留所需内存时返回的地址(sizeof(byte)* x):http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.13.html#malloc

答案 2 :(得分:1)

在定义中

char arrays[x][y];

y应该始终是const。这绝对没有例外。其他维度 - x只能在某些编译器上的堆栈上定义对象时才是变量。