gpt4 book ai didi

C- printf() 正在覆盖我的变量

转载 作者:太空宇宙 更新时间:2023-11-04 02:03:53 25 4
gpt4 key购买 nike

我正在进行练习,似乎 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- printf() 正在覆盖我的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23051720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com