**问题概述**
我当前遇到的问题是我有一个数组,其中的变量大小恰好是文件中的行数。这是一个计算并返回的整数,它成为数组大小(例如文件 text.txt 有 12 行,因此数组大小为 12)。
我想知道如何将此值返回到另一个 c 文件以在函数中使用,以便我可以循环访问完整的数组。
注意事项
- 在此作业中根本不允许使用任何全局变量,根本不允许使用全局数组/变量。
- 行计数功能正常工作,所以我不会在这里发布
- 数组设置正确并打印正确的结果
- 函数中的大部分代码已被删除,以便于阅读。
- 每个文件都有正确的 #includes,我只需要一个如何执行此操作的示例。
代码:
void read_from_file() {
/* reading and parsing removed */
no_of_lines = (count_lines(locof) - 1);
/* locof is a char array storing the file name */
ship ships[no_of_lines];
/* i want to return the value of no_of_lines *?
我想返回 no_of_lines 的值
我需要值的c文件
/*This is where i need the variable */
void asign_mayday_to_ships() {
int* ship_arr_length = SIZE OF SHIP ARRAY NEEDED
mayday_call* mday_ptr;
ship* ship_ptr; /* this is a ship array */
mday_ptr = read_mayday_file();
ship_ptr = read_ship_locations();
int i;
for(i = 0; i < SIZE OF SHIP ARRAY; i++){
}
最佳答案
只需传递指针和大小,这是 C 方式。
void read_from_file() {
/* reading and parsing removed */
no_of_lines = (count_lines(locof) - 1);
/* locof is a char array storing the file name */
ship ships[no_of_lines];
some_fun_from_second_file(ships, no_of_lines);
关于C 将数组的大小传递给另一个 C 文件变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20084541/