我正在做一个练习,似乎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;
};

提前谢谢你的帮助。我并不反对我的整个设计忽略了这一点。我可以更改结构定义和预期参数之外的任何内容。

最佳答案

当您这样做时:

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

wordPairs具有自动存储,其生存期将在函数返回时结束。试图在对象生命周期结束后引用它是未定义的行为,但是您在d中保留了指向它的指针,然后在dictionary_add()中尝试取消引用。
改用d->data = malloc(size * sizeof(struct wordpair *));或类似的词。不要忘记检查malloc()的返回以确定它是否成功,并且(通常)在完成后检查free()所有内容。

关于c - C- printf()正在覆盖我的变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23051720/

10-15 02:17