Inserting Value into an Array of Structures

Hello,

I am quite new to C++ and was hoping someone could help me with the following problem.

I seem to be getting an error message when I try and insert the word "Mocha" as a value into the first member of the array which consists of 3 structures entitled "CandyBar".

Any help would be greatly appreciated!

Kind Regards,

Giri

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
#include <iostream>

int main()
{

	using namespace std;

	struct CandyBar
	{
		char name[30];
		float weight;
		float calories;
	};

	CandyBar * pointer = new CandyBar[3];
	
        pointer[0].name = "Mocha";
	pointer[0].weight = 0.5;
	pointer[0].calories = 21.99;
	
	cout << pointer[0].weight << endl;

	cin.get();
	cin.get();

	return 0;

}

char arrays aren't strings, so you can't use them like that. Replace char name[30]; with std::string name; and add #include <string>
closed account (D80DSL3A)
The string class does make life easier. In case you must use character arrays ( an assignment requirement perhaps) then you need a special function which copies characters from one array to another. Replace line 17 with: strcpy(pointer[0].name, "Mocha");
Thanks so much guys!
Topic archived. No new replies allowed.