简体   繁体   English

将int数组复制到Struct int *

[英]Copying int array to Struct int*

Hi I'm trying to read variables from a file into a int array so I can store them in a Struct array. 嗨,我正在尝试将文件中的变量读取到int数组中,以便将它们存储在Struct数组中。 The numbers get stored correctly into the curLinks array but when I try pass the curLinks array into curNodes.nodes, it doesn't work and when i try print it out (to test) it prints rubbish numbers. 数字已正确存储在curLinks数组中,但是当我尝试将curLinks数组传递到curNodes.nodes时,它不起作用,当我尝试打印(测试)时,它会打印垃圾数字。 Any help would be great. 任何帮助都会很棒。

struct nodeInfo* getTopology(FILE *file){
    int totLinks=0;
    fscanf(file, "%d", &nodeCount);
    struct nodeInfo netTopo[nodeCount];

    // How many links does node have
    for (int id=0; id<nodeCount; id++){
        struct nodeInfo curNode;
        curNode.n=id;
        fscanf(file, "%d", &totLinks);
        int curLinks[totLinks];
        for(int i=0; i<totLinks; i++){
            int digit=0;
            fscanf(file, "%d", &digit);
            curLinks[i] = digit;
        }
        curNode.nodes = curLinks;

        netTopo[id] = curNode;
    }
    for (int id=0; id<nodeCount; id++){
        for (int j=0; j<3; j++){
            printf("%d ", netTopo[id].nodes[j]);
        }
    }

    return netTopo;
}

You define curLinks multiple time in the first for -loop 您可以在第一个for curLinks多次定义curLinks

int curLinks[totLinks];

And after you fill that you try to set that in your nodeinfo however as soon as the next iteration in the for -loop is entered and curLinks is filled again, the memory of your previous curLinks is out of scope and the memory where you think your read in values should reside can be actually filled with anything - Undefined Behaviour 并填充后,尝试在nodeinfo设置该值,但是一旦输入for -loop中的下一个迭代并再次填充curLinks ,则先前的curLinks的内存就超出范围,而您认为您的内存就超出了范围读取的值应驻留的位置可以实际填充任何内容- 未定义行为

If you tell me the way you define your structs nodeInfo I might be able to show you how to do it properly. 如果您告诉我定义结构nodeInfo我也许可以向您展示如何正确执行。

eg: Assuming you define 例如:假设您定义

struct nodeinfo {
    int *nodes;
};

Then 然后

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

    // How many links does node have
    for (id=0; id<nodeCount; id++){

        fscanf(file, "%d", &totLinks);

        netTopo[id].nodes = malloc(totLinks * sizeof(int));
        if (netTopo[id].nodes==NULL)
            printf("Error allocating memory\n");

        for(i=0; i<totLinks; i++) {
            fscanf(file, "%d", &digit);
            netTopo[id].nodes[i] = digit;
        }
    }

    // Free the allocate memory
    for (id=0; id<nodeCount; id++){
         free(netTopo[id].nodes);
    }

    return netTopo;
}

我认为在这种情况下,应该使用指针和“ malloc”从堆中分配内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM