Passing struct arrays to functions

The following example is discussed in the tutorial on this link:

http://www.cplusplus.com/doc/tutorial/structures/

I have two confusions here.
1) The function is taking an array of struct(movies_t) as input, but the function declaration is like that it is taking a normal object/variable of type movies_t.
 
void printmovie (movies_t movie);

Should it not be declared as
 
void printmovie (movies_t movie[]);

with brackets?

2) Also when the function is called from the main, the following statement is used
 
 printmovie (films[n]);

should it not be instead
 
 printmovie (films);

as brackets "[]" are optional here?

I am referring to the topic of "Arrays" in the tutorial given on following link:
http://www.cplusplus.com/doc/tutorial/arrays/


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  // array of structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct movies_t {
  string title;
  int year;
} films [3];

void printmovie (movies_t movie);

int main ()
{
  string mystr;
  int n;

  for (n=0; n<3; n++)
  {
    cout << "Enter title: ";
    getline (cin,films[n].title);
    cout << "Enter year: ";
    getline (cin,mystr);
    stringstream(mystr) >> films[n].year;
  }

  cout << "\nYou have entered these movies:\n";
  for (n=0; n<3; n++)
    printmovie (films[n]);
  return 0;
}

void printmovie (movies_t movie)
{
  cout << movie.title;
  cout << " (" << movie.year << ")\n";
}

Should it not be declared as

No, printmovie() is printing a single movie so the example is correct. Notice on line 30 in your post how it is being called within the loop and is using a single instance (films[n]).


should it not be instead
printmovie (films);
as brackets "[]" are optional here?

No without the brackets here you would be trying to send the address of the entire array to the function not a single instance. And no the brackets are necessary because this function is printing a single instance not the entire array.

OK. Thanks alot.
Topic archived. No new replies allowed.