Reputation: 203
How to access array of structure in another file.lets say i have 3 file 1.h 2.cpp 3.cpp as below
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();
}
i 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?
}
here i am getting errir as p and s are non of class type please help me to fix it
i am compiling as g++ 2.cpp 3.cpp
Upvotes: 0
Views: 2405
Reputation: 206717
I suggest the following changes:
Changes to 1.hpp
.
#include <stdio.h>
. you don't need it.Provide a declaration for the array, not a definition.
struct st
{
int i; // You had Int, not int. I assume that was a typo.
char ch[10];
};
extern struct st var[10];
Changes to 2.cpp
. Provide a declaration for callotherfile
before you use it.
#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
}
Changes to 3.cpp
.
#include <iostream>
. You need it to use std::cout
and std::endl
.cout
and endl
with the std::
scope.var
is an array, use var[p].i
instead of var.i
.Stop the loop when the loop counter reaches p
, not when it exceeds p
. Please note that 10
is not a valid index for an array with 10
elements.
#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;
}
Upvotes: 1
Reputation: 4805
Changes you need to do
1 #include "1.h" in
3.cpp
this might be a typo but this will also not solve ur problem just to note2 You need to include
3.cpp
in the file '2.cpp'3 compile it using this command 'g++ 2.cpp'
4 callotherfile(): put semicolon ; here
5 cout<<var.i<<end
put semicolon ; at the end
Upvotes: 0