Let's have a structure structure_s with elements par1 (int) and par2[] (int array). and in the function we have to at a specific index in structures[m] found out the sumn of par2? How do you do it?
int function(struct structure_s *ps){
//something that determinates index
for(int j = 0; j < m; j++){
//and now how do I get to the structures[index].par2[j]
}
}
//the variables n and m are known beforehand
struct structure_s{
int par1;
int par2[n];
}
int main(void){
struct structure_s structures[m];
int sum = function(structures);
//etc.
Unfortunately, they didn't show this at class and I can't find much useful information.
I have tried using like (*(ps + index)).par2[j]
, but it doesn't works, it says pointer to undefined type. I also thought maybe when I pass it to function should be &structures, but still the same mistake. Also (*p)[index].par2[j]
and (*(p)[index]).par2[j]
, but no idea what to use. Any ideas how to do it?
Edit, SOLUTION: I am stupid, thank you all for the help, it's nice knowing pointers can be noted like arrays and the problem was: not defining struct before function. You learn something new everyday.
int function(struct structure_s *ps){ //something that determinates index for(int j = 0; j < m; j++){ //and now how do I get to the structures[index].par2[j] } }
[...]
it says pointer to undefined type
Your structures[index].par2[j]
attempt is well-formed for the structure type you have presented, but you need to have the definition of that type in scope at the point where you use it. Your example code shows the type definition after the function, and if that faithfully reflects your real code then it is the source of the problem. Make sure the structure definition appears before the function.
In fact, it is fairly conventional to lay out C source files something like this:
#include
s for required headers
Local macro definitions not obtained from a header
Local type definitions not obtained from a header
File-scope variable definitions, if any (non-definition declarations should come from a header)
Any needed forward declarations of local functions not obtained from a header
Function definitions
Variations are possible, of course, but that tends to get things in the order you need them.