多个struct变量无意中被赋予相同的值

时间:2014-11-12 05:39:30

标签: c struct

我的程序有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中的main.c函数:

#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  

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

1 个答案:

答案 0 :(得分:1)

问题是你的setter和getter函数都在全局变量obj上运行。在您致电newstructure三次后,obj指向str3。因此,您的所有集合和获取只会影响str3。解决这个问题的方法是让你的setter和getter函数采用结构参数并对该参数进行操作而不是全局。