嘿我不确定为什么当我将一个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]);
......
答案 0 :(得分:2)
所以你从getTopology()返回一个指向堆栈本地var的指针?这就是错误。
netTopo在堆栈上,当你从getTopology()返回时,还有其他函数调用会重用存储netTopo的内存区域。修改了内存,调用nodeExecution()
时会得到不同的输出ADD:要解决此问题,您可以在getTopology()中分配内存:
struct nodeInfo* getTopology(FILE *file){
int id, digit=0, totLinks=0;
fscanf(file, "%d", &nodeCount);
struct nodeInfo * netTopo = malloc(sizeof(struct nodeInfo)*nodeCount);
....