gpt4 book ai didi

c - 多个结构变量无意中被分配了相同的值

转载 作者:行者123 更新时间:2023-11-30 20:26:04 24 4
gpt4 key购买 nike

我的程序有一个struct,其中包含2个变量和3个函数指针,如下文件demo.h:

#ifndef DEMO_H
#define DEMO_H



typedef struct {

int structNumber;
char *name;

void (* setName)(char *);

int (* getStructNumber)();
char *(* getName)();
} *structure;



structure newStructure(); // This function builds an object kind of, of the structure and returns a pointer to it.


#endif

这些函数的实现在demo.c中:

#include "demo.h"
#include <stdlib.h>



structure obj; // Theres definitely something wrong with the usage of this variable in function newStructure().



void setName(char *name) {

obj->name = name;
}



char *getName() {

return obj->name;
}


int getStructNumber() {

return obj->structNumber;
}



structure newStructure() {

static int structNumber = 0;
structNumber ++;

structure ob = (structure)malloc(sizeof(*ob));

// Actually I've used this obj variable
// so that this ob is accessible in other functions too.
// But I suppose I am not using it properly.
// I don't wish to pass ob as a parameter to other functions.
// The program works fine if I pass it as parameters.
// But I want to do it without passing it as parameters.
obj = ob;

ob->structNumber = structNumber;


// Assigning the function pointers.
ob->setName = setName;
ob->getStructNumber = getStructNumber;
ob->getName = getName;


return ob;
}

这是文件 main.c 中的 main 函数:

#include "demo.h"
#include <stdio.h>



int main() {

void displayData(structure);

structure str1 = newStructure();
structure str2 = newStructure();
structure str3 = newStructure();

str1->setName("Robin Hood");
str2->setName("Tiger Woods");
str3->setName("William Shakespeare");

displayData(str1);
displayData(str2);
displayData(str3);

return 0;
}



void displayData(structure str) {

int structNumber = str->getStructNumber();
char *name = str->getName();

fprintf(stdout, "Struct number = %d\n", structNumber);
fprintf(stdout, "Name: %s\n", name);
}

上述程序所需的输出是:

Struct number = 1
Name: Robin Hood
Struct number = 2
Name: Tiger Woods
Struct number = 3
Name: William Shakespeare

但输出实际上是这样的:

Struct number = 3
Name: William Shakespeare
Struct number = 3
Name: William Shakespeare
Struct number = 3
Name: William Shakespeare

所有三个结构变量都具有相同的值。
我应该如何获得所需的输出?
请帮忙!提前致谢!

最佳答案

问题在于您的 setter 和 getter 函数都对全局变量 obj 进行操作。三次调用 newstruct 后,obj 指向 str3。因此,您的所有设置和获取都只会影响 str3。解决此问题的方法是让您的 setter 和 getter 函数采用结构参数并对该参数(而不是全局参数)进行操作。

关于c - 多个结构变量无意中被分配了相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26880027/

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