2

嘿,我不确定为什么当我将 Struct 数组传递给函数时;当我尝试访问它的成员时,它会打印随机数。在语句“printf("%d\n", netTopo[0].nodes[1]);"下面 工作正常,但我在函数中并尝试打印相同的数据,它会打印一堆随机数?不知道我做错了什么。

int main(int argc, char *argv[]) {

if (argc != 3){
        printf("Incorrect command line arguments. Required 2 files.\n");
        exit(-1);
    }

    FILE *netFile, *schFile; // put into a loop
    netFile = fopen(argv[1], "r");
    schFile = fopen(argv[2], "r");

    int *sched = getSchedFile(schFile);

    struct nodeInfo *netTopo = getTopology(netFile);
    printf("%d\n", netTopo[0].nodes[1]);

    int nodeSocks[nodeCount];
    for (int i=0; i<nodeCount; i++){
        nodeSocks[i]=getSocketNo();
    }

    get_elapsed_time(); // start clock

    for (int i=0; i<nodeCount; i++){
        if (fork()==0){
            nodeExecution(i, nodeSocks, netTopo, sched);
            exit(0);
        }
    }
}

void nodeExecution(int id, int nodes[], struct nodeInfo *netTopo, int *schd){
    printf("%d\n", netTopo[0].nodes[1]);
......
4

1 回答 1

2

所以你从getTopology()返回一个指向堆栈上本地变量的指针?这就是错误。

netTopo 在堆栈上,当您从 getTopology() 返回时,还有其他函数调用将重用存储 netTopo 的内存区域。该内存已修改,并且在调用 nodeExecution() 时会得到不同的输出

添加:要解决此问题,您可以在 getTopology() 中分配内存:

struct nodeInfo* getTopology(FILE *file){
    int id, digit=0, totLinks=0;
    fscanf(file, "%d", &nodeCount);
    struct nodeInfo * netTopo = malloc(sizeof(struct nodeInfo)*nodeCount);

  ....
于 2013-10-12T07:23:46.870 回答