C 将数组的大小传递给另一个 C 文件变量

标签 c arrays

**问题概述**

我当前遇到的问题是我有一个数组,其中的变量大小恰好是文件中的行数。这是一个计算并返回的整数,它成为数组大小(例如文件 text.txt 有 12 行,因此数组大小为 12)。

我想知道如何将此值返回到另一个 c 文件以在函数中使用,以便我可以循环访问完整的数组。

注意事项

  1. 在此作业中根本不允许使用任何全局变量,根本不允许使用全局数组/变量。
  2. 行计数功能正常工作,所以我不会在这里发布
  3. 数组设置正确并打印正确的结果
  4. 函数中的大部分代码已被删除,以便于阅读。
  5. 每个文件都有正确的 #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/

相关文章:

c++ - 嵌入式系统的开源视频编码器

c++ - 需要多个数独解决方案

c# - 将被点击的标签传递给它的点击方法。 C#

arrays - 如何使用百分比表示法在 ruby​​ 中制作整数数组?

c - 无法从 C 文本文件中读取结构

c - 无论我做什么,While 循环都不会中断

mysql - 从表中的多个值中选择不在数组中的位置

c++ - CUDA:处理不同大小的数组

我可以使用 & 运算符在函数中获取有效指针,即使该函数已在 golang 中返回

java - 一个文本文件出现数组索引越界异常,但 Java 中的另一个类似文件却没有出现数组索引越界异常?