C-printf()正在写我的变量

时间:2014-04-14 03:58:45

标签: c pointers struct

我正在练习练习,似乎printf()正在某处编写我的变量。我正在使用一个包含指向结构指针数组的指针的结构,所以我确定我已经在某处稍微分配了一些错误。

    int dictionary_add(struct dictionary* d,
                    const char * const english,
                    const char * const foreign){
    /* ROLE         Adds a new wordPair made of strdup copies of the parameter strings
                    to a dictionary d

       RETURNS      0   if everything went fine

       PARAMETERS   d           the dictionary to work with
                    english     string representing the english part of the new wordPair
                    foreign     string representing the foreign part of the new wordPair
    */




    //Determine where in the array the wordPair is going.
    int location;
    location=((d->size)-(d->nbwords))-1;
    printf("Adding data to array location: %i\n\n",location);


    //Build the wordPair
    const struct wordPair newPair={english,foreign};

    //Add the wordPair
    d->data[0]=&newPair;

    //***************This is where the problem shows up***************
    printf("Added english:%s\n",d->data[0]->englishWord);
    //d->data[0]=&newPair; //When uncommeted, program doesn't crash.
    printf("Added english:%s\n",d->data[0]->englishWord);
    d->nbwords++;
    return 0;
}

如何从main()调用它:

const char* english=malloc(sizeof(char)*6);
const char* foreign=malloc(sizeof(char)*6);
strcpy(english,"hello");
strcpy(foreign,"holla");

创建字典的地方:

    struct dictionary *dictionary_build(int size){
     /* ROLE        Allocate and initialize a new dictionary structure able to accomodate a number of
                    pairs of words specified by the size parameter
       RETURNS      Address of new dictionary, if allocation was successfull.
                    NULL otherwize
       PARAMETERS   The size of the dictionary to make
     */
    struct dictionary *d=malloc(sizeof(struct dictionary));

    d->size=size;
    d->nbwords=0;

    struct wordpair* wordPairs[size]; //create array of pointers to wordpairs


    d->data=&wordPairs; //Set pointer to array of pointers to wordpairs

    return d;
}

结构:

struct wordPair {
       char* englishWord;
       char* foreignWord;
};

struct dictionary {
       struct wordPair ** data;
       int nbwords;
       int size;
};

提前感谢您的帮助。而且我并不反对我的整个设计错过了重点的想法。我可以更改结构定义和预期参数之外的任何内容。

1 个答案:

答案 0 :(得分:3)

执行此操作时:

    struct wordpair* wordPairs[size];
    d->data=&wordPairs;
    return d;
}

wordPairs具有自动存储功能,其生命周期将在函数返回时结束。尝试在对象生命结束后引用该对象时未定义的行为,但是您在d中保留了指向它的指针,然后您尝试在dictionary_add()中取消引用。

使用类似d->data = malloc(size * sizeof(struct wordpair *));或类似内容的内容。不要忘记检查来自malloc()的回报,以确定它是否成功,并且(通常)free()当您完成后的所有内容。