[英]Passing pointer/array to main() from a function
I'm learning functions/pointers, and having a bit of an issue. 我正在学习函数/指针,并且遇到了一些问题。 What I need to write is a C program with
main()
and two other functions. 我需要编写的是一个带有
main()
和另外两个函数的C程序。
read_funct()
must allocate enough memory using malloc()
to store the data. read_funct()
必须使用malloc()
分配足够的内存来存储数据。
Function prototype for read_funct
must be: read_funct
函数原型必须是:
int read_funct(int *data_num, double **data_vals, char *filename)
main()
calls the first function: read_funct()
main()
调用第一个函数: read_funct()
read_num()
reads binary data from a file. read_num()
从文件中读取二进制数据。 Two values have to be extracted: the no. 必须提取两个值:no。 of values (first 4 bytes), then the values themselves (8 bytes each, so contained in the next 8*no. of values).
值(前4个字节),然后是值本身(每个8个字节,因此包含在下一个8 *值的值中)。 These correspond to
data_num
and data_vals
. 这些对应于
data_num
和data_vals
。 They have to be printed, the program then returns to main()
. 必须打印它们,然后程序返回
main()
。
main()
performs operations to edit the data from the first file. main()
执行操作以编辑第一个文件中的数据。
main()
calls the second function: write_funct()
, which writes the edited data into a new file. main()
调用第二个函数: write_funct()
,它将编辑后的数据写入新文件。
The first function reads data_num
correctly, and reads/prints data_vals
. 第一个函数正确读取
data_num
,并读取/打印data_vals
。 This is all working properly. 这一切都正常。 However, I'm trying to print these in
main()
to verify that I'm performing operations on the correct data, but I can't get it working. 但是,我正在尝试在
main()
打印这些,以验证我正在对正确的数据执行操作,但我无法使其正常工作。
Note: I'm not trying to get it working with write_funct()
at the moment, just taking it step-by-step. 注意:我现在并没有尝试使用
write_funct()
,只是逐步进行。
Here's my current code for main()
: 这是我当前的
main()
代码:
int read_funct(int *data_num, double **data_vals, char *filename);
int main()
{
int data_num;
double **data_vals;
//Reads file using read_funct()
read_funct(&data_num, data_vals, filename);
//Check: print data_num
printf("\nCheck No. of Values: %d\n", data_num);
//Check: print data_vals
for(int i = 0; i<data_num; i++)
{
printf("%0.3lf\t", data_vals[i]);
}
return(0);
}
Here's read_funct(
) 这是
read_funct(
)
int read_funct (int *data_num, double **data_vals, char *filename)
{
FILE * fp = fopen(filename, "rb"); //Opening file
//There's code here to check valid file open
//There's code here to determine size and check valid length
//Proceed with reading data_num if file is large enough
char buffer_n[4];
fread(buffer_n, 4, 1, fp);
int res = buffer_n[0]|(buffer_n[1] << 8)|(buffer_n[2] << 16)|(buffer_n[3] << 24); //Convert endian
data_num = &res; //Passes results back to data_num
printf("Number of Data Values: %d \n", *data_num); //Printing results
//Proceeds with calculating data_vals
data_vals = malloc(8*res); //Allocating memory
fread(data_vals, 8, res, fp);
//Prints data_vals
for(int i=0; i<res; i++)
{
printf("%0.3f\t", data_vals[i]);
}
printf("\nEnd of File Read.\n\n");
fclose(fp);
free(data_vals); //Free allocated memory
return(0);
}
Basically, I want it to print out the values from inside read_file()
and then print a check in main()
, so the output will be something like: 基本上,我希望它从
read_file()
内部打印出值,然后在main()
打印一个检查,所以输出将是这样的:
No. of values: 3 //From printf in read_file()
2 4 6
Check No. of values: 3 //From printf in main()
2 4 6
Fairly sure that the main issue is that I've messed up my pointers and how I've initialised things in main()
. 相当确定的主要问题是我搞砸了我的指针,以及我如何在
main()
初始化东西。 I've been trying to fix this by myself, but I think I need some more experienced help to figure this out. 我一直在努力解决这个问题,但我认为我需要一些更有经验的帮助来解决这个问题。
I know that every malloc()
call must have a subsequent free()
, but I'm worried that by doing so the way that I have, maybe I've made it so that I can't retrieve it in main()
. 我知道每个
malloc()
调用必须有一个后续的free()
,但我担心这样做的方式,也许我已经做到了这样我无法在main()
检索它。 Does it instead need to have an intermediate buffer to which memory is allocated instead? 是否需要有一个分配内存的中间缓冲区?
Help to get this code working would be very greatly appreciated. 将非常感谢帮助使此代码正常工作。 Thank you!
谢谢!
Apart from freeing the data too soon, you have another problem here: 除了过早释放数据外,您还有另一个问题:
double **data_vals;
read_funct(&data_num, data_vals, filename);
If you want data_vals
to be filled (written to, modified) by a function, you must pass its address, exactly as you do with data_num
. 如果希望
data_vals
填充(写入,修改) data_vals
,则必须传递其地址,就像使用data_num
。
Here is another, slightly different, explanation. 这是另一个略有不同的解释。 You see, you declare
data_vals
but you don't assign a value to it - it contains garbage. 你看,你声明了
data_vals
但你没有给它赋值 - 它包含了垃圾。 So it is a non-sense to pass data_vals
to any function, or use it in any expression. 因此,将
data_vals
传递给任何函数或在任何表达式中使用它都是没有意义的。 It has a sense instead, to assign something to it, either via direct assignment or passing its address to a function, for the function to fill the variable. 相反,通过直接赋值或将其地址传递给函数来为函数填充变量赋予它一些意义 。
Then, your usage of data_vals
depicts a vector, or an array. 然后,您对
data_vals
的使用描绘了一个向量或一个数组。 So you really need to declare an array with []
, or may be a pointer (pointers and arrays are quite related/interchangeable in C). 所以你真的需要用
[]
声明一个数组,或者可能是一个指针(指针和数组在C中非常相关/可互换)。 The logic of your main() function requires a pointer, not a pointer to pointer . main()函数的逻辑需要指针,而不是指向指针的指针 。 Hence, this is appropriate:
因此,这是合适的:
double *data_vals;
The function which writes to your pointer variable, instead, needs the address of the variable to write to; 相反,写入指针变量的函数需要写入变量的地址; in other words: a pointer to a pointer .
换句话说: 指向指针的指针 。 This is why your function has this (correct) signature:
这就是您的函数具有此(正确)签名的原因:
read_funct(..., double **data_vals, ...)
To understand easily, let see the other (simpler) thing you wrote correctly: 要轻松理解,请查看您正确编写的其他(更简单)的内容:
int data_num;
read_funct(&data_num, ...); // declaration: read_funct(int *data_num, ...)
You declare data_num
as integer in main(); 在main()
data_num
声明为整数; you declare read_funct() with a formal parameter of pointer to integer , then you call read_funct() passing the address of your variable data_num
. 使用指向整数的指针的形式参数声明read_funct(),然后调用read_funct()传递变量
data_num
的地址 。 Perfect. 完善。 Now, do the same with the other variable,
data_vals
. 现在,对其他变量
data_vals
执行相同的data_vals
。 You declare it as pointer to double , pass its address to read_funct() using the notation &data_vals
, and your function read_funct() declares that parameter as a pointer to pointer to double (and writes to it using *data_vals = ...
. You can see the parallelism between the two variables, right? 您将其声明为double的指针 ,使用符号
&data_vals
将其地址传递给read_funct(),并且函数read_funct()将该参数声明为指向double的指针 (并使用*data_vals = ...
写入它。可以看出两个变量之间的并行性吧?
May be I've been too pedantic, but your question was really clear and well formed, so I tried to do the same. 可能是我太迂腐了,但你的问题非常清楚,形成得很好,所以我试着做同样的事情。
Yes, you are free-ing the buffer too soon. 是的,你过早地释放缓冲区了。 After you have freed it, there is not guarantee as to what it contains.
在释放它之后,不能保证它包含什么。 You can free it at the end, in main.
你可以在主要结束时释放它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.