c++ - 如何访问另一个文件中的结构数组

标签 c++ structure

如何访问另一个文件中的结构数组。假设我有 3 个文件 1.h 2.cpp 3.cpp,如下所示

1.h

    #include<stdio.h>
    struct st
  {
       Int i;
        char ch[10];

    };
   struct st var[10];

2.cpp

   #include"1.h"
     int main
     {
        int s;
       //here i hve scannd value of i frm user
       callotherfile();
      }

我 3.cpp

    #include"1.h
     int p;
       void callotherfile(void)
      { 
        for(p=1;p<=10;p++)
       cout<<var.i[p]<<end;// is it good can i excess?
      }

这里我遇到了错误,因为 p 和 s 不是类类型,请帮助我修复它

我正在编译为 g++ 2.cpp 3.cpp

最佳答案

我建议进行以下更改:

  1. 1.hpp 的更改.

    1. 删除 #include <stdio.h> .你不需要它。
    2. 为数组提供声明,而不是定义。

       struct st
       {
          int i; // You had Int, not int. I assume that was a typo.
          char ch[10];
       };
       extern struct st var[10];
      
  2. 2.cpp 的更改.为 callotherfile 提供声明在使用之前。

    #include "1.h"
    void callotherfile(void);
    int main()
    {
       int s;  // This is an unused variable. It can be removed.
       callotherfile(); // You had a : not a ;. I assume that was a typo
    }
    
  3. 3.cpp 的更改.

    1. 添加#include <iostream> .您需要它才能使用 std::coutstd::endl .
    2. 提供数组的定义。
    3. 使用coutendlstd::范围。
    4. var是一个数组,使用var[p].i而不是 var.i .
    5. 当循环计数器达到p时停止循环,而不是当它超过 p 时.请注意 10不是具有 10 的数组的有效索引元素。

      #include <iostream>
      
      #include "1.h"
      struct st var[10];
      int p;  // This variable can be moved to the function scope.
      void callotherfile(void)
      { 
         for(p=1;p<10;p++) // You had p<=10
            std::cout<<var[p].i<<std::endl;
      }
      

关于c++ - 如何访问另一个文件中的结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26601586/

相关文章:

c++ - 如何检测模板参数是否是内置的?

c++ - 最后一个关联处理程序之后的变量

c - 结构新手,为什么我的程序没有运行?

c - 队列数据结构实现

c++ - C++ 中的 vector 与数组?

c++ - openGL中的全透明对象

c++ - 比较复杂的结构

python - Python 代码的结构

c - 结构元素自由函数

c++ - Cmake - 如何复制带有输入数据的文件以构建输出文件夹