Printing an array of string with the help of struct

Hello. I am trying to print the two strings but it seemed to have an error. I am new in learning structures which is why I am having difficulty in testing. Any help is appreciated!

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
#include<iostream>
#include<string>
#include<iomanip>
#include<cstring>
using namespace std;
struct Computer
{
	
	string pc[3];
	string motherboard;
	string processor[2];

};

int main(){
	

	
	Computer computer;
	
	computer.processor[2] = {"Intel", "Lenovo"};
	
	for(int i = 0; i< 2; i++)
	{
		cout << computer.processor[i] << endl;
	}

}//end main 
On line 21, you are not initializing your processor array. You are assigning to the third element (index 2) of the processor array, which is out of bounds of the array.

Unfortunately, when you put a C-style array into a struct/class like that, it limits the ways you can initialize it, because it's already initialized on line 19 when you created the object itself.

Here is one way you can initialize the array. Otherwise, you have to assign to each array index individually (processor[0] and processor[1]).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
#include<string>
#include<iomanip>
#include<cstring>
using namespace std;
struct Computer
{	
	string pc[3];
	string motherboard;
	string processor[2];
};

int main(){	
	Computer computer = {
	    {}, // pc array init (3x empty strings)
	    {}, // motherboard init (empty string)
	    {"Intel", "Lenovo"} // processor array init	    
	};

	for(int i = 0; i< 2; i++)
	{
		cout << computer.processor[i] << endl;
	}
}
Last edited on
@Ganado ohhh I see thanks. You are a huge help man. I still have a lot to learn in using struct!
Last edited on
Topic archived. No new replies allowed.