因此,根据我对 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
未在函数内部声明,但您可以访问它。这意味着它被声明为全局变量,并且可以从源文件内的任何位置访问。
如果您在函数内部声明了此变量,那么您需要将其地址传递到函数中才能修改它。
关于C 附加到结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50029265/