C中结构的全局数组的意外输出

时间:2019-03-26 20:10:35

标签: c struct malloc global-variables header-files

我试图操纵一个动态分配的结构体数组,但是尽管它是一个全局变量,但我无法在函数调用之间保存数据。我正在使用头文件来声明全局变量,与函数实现的头文件同名的文件以及运行程序的主文件。这是三个文件的内容:

things.h:

struct st {
    int number;
};

struct st *test;

// Function Declarations
int A();
int B();

things.c:

#include <stdio.h>
#include <stdlib.h>
#include <things.h>

    int A() {

        // Allocate size for 10 struct st's
    test = malloc(10*sizeof(test));
    test[5].number = -1;
    printf("%d\n", test[5].number);

    B();

    return 0;
}


int B() {

    printf("%d\n", test[5].number);

    return 0;
}

mainFile.c:

#include <stdio.h>
#include <stdlib.h>
#include <things.h>

int main() {

    A();

    return 0;
}

不确定是什么问题。预期的输出是:

-1
-1

但是我得到的输出是:

`-1`
`some-random-number-here`

这是我实际工作的非常简单的副本,因此不必担心动态分配(必须是动态的)并检查它是否首先返回NULL。

编辑:

就像@xing和@cdarke提到的那样,我的问题是我的malloc。现在按预期工作。

0 个答案:

没有答案
相关问题