我一直在重写一些函数以返回 int 而不是结构,以便我可以做到这一点
if ( function(&struct1,vars) != 0 )
{
// die and give error
}
而不是:
然而,我在这里缺少一些概念,因为每当我尝试访问主结构中的结构值时,我都没有获得在函数中分配给它的值。如果有人能向我解释我的内存/变量到底发生了什么(我会写下我认为发生的事情)以及为什么它不起作用,我将不胜感激。struct = function(vars);
主要(缩短):
int main (int argc, char *argv[]) {
arguments args;
data data;
scan scans;
printf("Value at start %i\n",scans.number);
if (scan_extractor(&args,&scans) != 0) // Pass the reference of the struct to scan_extractor (while still being un-initilizaed, something I don't quite grasp).
{
printf("Error in argument reader\n");
exit(0);
} else {
printf("Main thinks %i scans\n",scans.number);
}
return(0);
}
函数(scan_extractor):
int
scan_extractor(arguments* args, scan* scans)
{
FILE* fr;
int counter = 0;
fr = fopen(args->scans,"r");
scans = calloc(MAX,sizeof(scan)); // Allocate memory to store multiple instances of the scan object
while (fgets(mzML_buffer,MAX_BUFFER,fr) != NULL)
{
(scans+counter)->id = atoi(mzML_buffer); // Modify the global version of scans
counter++;
}
scans->number = counter;
printf("Function read %i scans\n",scans->number);
return(0);
}
读取的文件包含 1 行,其中包含值 1
我得到的输出是:
Value at start 32767
Function read 1 scans
Main thinks 32767 scans
为什么这让我发疯是因为可以使用类似的语法从 main 访问包含输入参数的几乎相同的代码块(仅结构参数的 char* 值与结构扫描的 int 值)。
最佳答案
scan_extractor(arguments* args, scan* scans)
scans = calloc(MAX,sizeof(scan));
您正在将内存分配给正在传递的指针的副本。能够为函数内部的指针分配内存。您需要通过引用传递指针:
scan_extractor(arguments* args, scan** scans)
*scans = calloc(MAX,sizeof(scan));
再考虑一下。你的程序没有意义。您正在混合两个概念。
您在本地存储上分配一个 scan
对象并将其地址传递给该函数。在函数内部,您将动态内存分配给指针本地的函数,该指针先前指向传递的对象。这只会泄漏内存,而基于堆栈的 scan
对象永远不会被填充
基本上,您只需要传递对象的地址并使用该对象。它已经被分配了,不需要在函数内部分配。
scan scans;
if (scan_extractor(&args,&scans)
scan_extractor(arguments* args, scan* scans)
scans->number = counter;
关于c - 通过引用函数传递结构、操作它们并从 'main' 访问它们的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14482061/