c++ - 段错误 - 从指针到指针的 printf 值

标签 c++ c struct

我试图在这里找到问题 - 在这个函数中:

void PrintDic(dictionary **head)
    {
        dictionary *current = *head;
        if(current->nexdic==NULL)
            printf("empty dictionary\n");
        else
        {
            while(current->nexdic!=NULL)
            {
                int i;
                for(i=0;i<1; i++)
                    printf("%s\n",current->word);
                current=current->nexdic;
            }
        }
    }

在 Visual Studio 中它可以工作,但在 Linux 中它总是给我一个段错误。

结构:

struct dictionary
{
    char word[MAXLETTERS];
    char** year;
    int countyear;
    char** synonyms;
    int countsyn;
    char** def;
    int countdef;
    struct dictionary*nexdic;

};

add函数:(向struct中插入值,按字典序查找位置添加struct =链表!)

void Add(char* word, char * year,int countyear, char*syn, int countsyn, char* def,int countdef, dictionary** head)
{
    dictionary*next;
    //add new entry
    dictionary*newentry=(dictionary*)malloc(sizeof(dictionary));
    if(CheckNull(newentry)==1)
        exit(1);
    int i;
    char *index;
    //insert word
    strcpy(newentry->word,word);
    //insert year
    char **toyear=(char **)malloc((countyear+1)*sizeof(char*));
    index=year;
    for(i=0;i<=countyear; i++)
    {
        toyear[i]=index;
        index=NextString(index);
    }
    newentry->year=toyear;
    //insert syn 
    index=syn;
    char **tosyn=(char **)malloc((countsyn+1)*sizeof(char*));
    for(i=0;i<=countsyn; i++)
    {
        tosyn[i]=index;
        index=NextString(index);
    }
    newentry->synonyms=tosyn;
    //insert definition
    index=def;
    char **todef=(char **)malloc((countdef+1)*sizeof(char*));
    for(i=0;i<=countdef; i++)
    {
        todef[i]=index;
        index=NextString(index);
    }
    newentry->def=todef;
    //set counts
    newentry->countyear=countyear+1;
    newentry->countsyn=countsyn+1;
    newentry->countdef=countdef+1;
    next=FindPlace(newentry->word,*head);
    if(next==NULL)
    {
        if(*head==NULL)
            newentry->nexdic=NULL;
        else
        {
            newentry->nexdic=*head;
        }
        *head=newentry;
    }
    else
    {
        newentry->nexdic=next->nexdic;
        next->nexdic=newentry;
    }
}

最佳答案

下面的代码有问题。

在while循环中,你的current变成了current->nexic,这不能NULL。对于下一次迭代,同时尝试访问您的 current (current->nexdic),它是 NULL,因此存在段错误。

    while(current->nexdic!=NULL)
    {
        int i;
        for(i=0;i<current->countdef; i++)
            printf("%s\n",current->def[i]);
        current=current->nexdic;
    }

我不知道你的程序逻辑,但你可以检查 while(current != NULL) 而不是 current->nexdic

关于c++ - 段错误 - 从指针到指针的 printf 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20975884/

相关文章:

c++ - 意外的重定位类型 0x03

c++ - Steam API 获取角色名称

c++ - 关于 C++ 中结构的模板

c - 对齐如何与指向零大小数组的指针一起使用?

c++ - 备用http端口?

c++ - 关于在 C++ 中将类作为别名参数传递的问题?

c - 结构内 C 字符串的 Malloc 内存

c - 线程结构作为函数参数 C

c++ - 将对象指针(之前创建的)传递给动态共享库的 extern "C"函数

c - c 中的链接结构