Putting a 1d array in a struct

Hey uys! I posted this before but still struggling. I would like to have a struct with 2 members in a 1d array.

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
  #include <iostream>
#include <string>
using namespace std;

struct Person
{
	string  name;
	string surname;
};


int main()
{
	Person personDetails[4];
	personDetails[4].name = "John","Peter","James";
	personDetails[4].surname = "Peter","John","Folley";

	for (int i = 0; i < 5; i++)
	{
		cout << personDetails[i].name << "/t" << personDetails[i].surname; 
	}

	system("pause");
	return 0;
}


My output should be
John Peter
Peter John
James Folley
Last edited on
The valid indices for an array that has N elements are in range [0..N-1].

On line 14 you declare an array with 4 elements.

On lines 15-16 you attempt to assign something to (non-existing) fifth element of the array. Assignment is not initialization.

On line 18 you iterate over 5 elements, but again you have only 4.

This might be better:
1
2
3
4
5
Person personDetails[] { { "John", "Doe" }, {"Jane", "Smith"} };

for ( const auto & p : personDetails ) {
  std::cout << p.name << '\t' <<p.surname << '\n';
}
Thanks! It worked. Is it still a 1d array and whenever you want to hardcode it, You don't write the number of the array in the brackets?
It is a 1D array.

I kind of wrote the number; the compiler calculates from the initialization list how many elements the array must have. That is a compile-time constant.

You could both write a number (X) into brackets and give an initialization list (for Y elements), but then you have three possibilities:
1. Y == X. That you get without writing the X too.
2. Y < X. Some elements are initialized with the values you give. The rest are value-initialized. For basic types that means zero-initialization.
3. Y > X. Syntax error.
Topic archived. No new replies allowed.