c附加到结构阵列

  • 本文关键字:结构 阵列 c function
  • 更新时间 :
  • 英文 :


因此,从我对C的理解中,如果您想在功能中永久更改某些内容,则必须将指针作为参数传递。但是,我有一定的代码,可以附加到一系列没有任何指针的结构上。

在其他文件中:

extern struct data *information;

在另一个文件中:

struct data *information 

在某些功能中:

information = malloc(sizeof(data));

最终所讨论的功能:

void function(int total, bool status){
        total++;
        char input[30];
        printf("Please enter some input...n>>>");
        scanf(" %[^n]s", input);
        //reallocate memory to fit new element
        information = realloc(information,sizeof(struct some_struct)*total); 

        //assign values to struct members
        strcpy(information[total-1].description,input);
        information[total-1].amount = total;

        return;
}

我通过添加一些示例来测试此功能,并在打印时在那里。我对这个错误的理解是错误的吗?

变量information在功能内部没有声明,但您可以访问它。这意味着它被声明为一个全局变量,可以从源文件中的任何地方访问。

如果您在函数内部声明了此变量,那么您需要将其地址传递到函数中才能修改。

全局变量意味着它可用于所有函数,而无需传递函数。无需通过全局变量。因此,变量不会在函数的本地堆栈上。因此,全局变量(在您的案例信息中(能够通过函数调用保留修改值。

最新更新