【问题标题】:Undeclared identifier when passing struct using pointers使用指针传递结构时未声明的标识符
【发布时间】:2013-04-24 10:26:23
【问题描述】:

我有以下方法可以将文件读入结构体,但是,由于curr 变量为空,因此程序在进入写入文件方法时会被炸毁。

当变量被标记时,我添加了一个空检查,但此时它没有抛出错误。我猜这与我将数据复制到newContact 的方式有关,但我看不出我在哪里搞砸了。

这是提到的方法,在文件中读取标记变量并添加newContact

struct contact *readFile(char * FName,struct contact** ptrList)
{    
    struct contact *head, *newContact;
    FILE *fptr;
    char oneLine[60];
    char *sname, *fname, *phone,*company, *email;

    head = *ptrList;

    fptr = fopen(FName,"r");

    if(fptr == NULL)
    {
        printf("\nCant open file!");
        return(ptrList);    
    }
    fgets(oneLine, 55, fptr);
    while(!feof(fptr))
    {
        fgets(oneLine, 55, fptr);
        if(oneLine[strlen(oneLine)-1] == '\n')
        {
            oneLine[strlen(oneLine)-1] = '\0';    
        }

        // open file and other stuff
        if(!ptrList) return; // invalid pointer
        for(head=*ptrList;head&&head->next;head=head->next);
        while( ReadLine(fptr,oneLine) )
        {
            //check that variables aren't empty here:
            if(sname == NULL || fname == NULL)
            {
                printf("\nvariable empty!");
                //return(ptrList);
            }
            sname = strtok(oneLine,",");
            fname = strtok(NULL,",");
            phone = strtok(NULL,",");
            company = strtok(NULL,",");
            email = strtok(NULL,",");

            newContact = (struct contact *)malloc(sizeof(struct contact));
            if(!newContact) break; // out of memory
            newContact->prev = head;
            newContact->next = 0;

            //copy the data to the new one
            strcpy(newContact->sname,sname);
            strcpy(newContact->fname,fname);
            strcpy(newContact->phone,phone);
            strcpy(newContact->company,company);
            strcpy(newContact->email,email);

            head = newContact;
            if(!*ptrList) *ptrList = head; // see: point 2
        }
    }

这是struct 声明:

struct contact {
    char sname[15];
    char fname[15];
    char phone[15];
    char company[15];
    char email[15];
    struct contact *prev;
    struct contact *next;
};

我在ReadLine 也收到了一个未定义的错误。是否有我应该为此功能导入的库(因为我在搜索中看不到任何提及)?

while( ReadLine(fptr,oneLine) )

新的错误发生在这里:

head = *ptrList;

关于它为什么被轰炸的任何想法?

【问题讨论】:

  • ReadLine 未定义或声明。
  • 是的,但是否有导入 ReadLine 作为其功能?
  • 显示崩溃发生的代码可能是个好主意。
  • gnu readline ?虽然情况会有所不同,readline vs ReadLine
  • 它有不同的用途。为什么ReadLine,你确定你没有把它和其他语言的函数混在一起吗?

标签: c pointers struct readline stringtokenizer


【解决方案1】:
head = newContact;
if(!*ptrList) *ptrList = head; // see: point 2

我相信,你已经在列表的末尾了。 我认为不需要这个“if”语句。我们永远不会改变列表的实际“头”,这就是“ptrList”所指向的地方。

另外,你不希望下面的“for”循环在第一个 while 循环之外吗? 该代码正在尝试从文件中读取并添加到列表的末尾。 我认为不需要遍历文件的每一行的循环。

 for(head=*ptrList;head&&head->next;head=head->next);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多