problem with char array in a exercise on pointers.

Hi, im new to c++ programming and need help to understand why this code isnt working.
I was trying to code an exercise on pointers and structures but couldnt get it to work.
i get this error message:
error C2440: '=' : cannot convert from 'const char [5]' to 'char [20]
I solved it by using string instead of char Array in the structure but im intrested in knowing why it isnt working with an char Array so i might learn something new.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

struct candybar
{
	char brand[20];
	double weight;
	int cal;
};

int main()
{
	candybar *p_candy = new candybar[3];

	p_candy[0].brand = "japp";
	p_candy[0].weight = 3.5;
	p_candy[0].cal = 500;
C-style arrays are not assignable, so the expression p_candy[0].brand = "japp";, which attempts to assign an array of 5 const char (four letters and a null char) to the array of 20 char cannot be compiled.

strings are assignable, which is why it worked for you with strings.
Hi lilysfather

You cannot assign char arrays like that.

In C, you must copy each char individually, or use a library function to do it.

As you have figured out, it is a lot easier in C++ to use strings ...... :-)

HTH

Last edited on
Ok, thanks for the fast answers.
It works if i initialize it to "japp" or use cin >> to get user input.
But i cant assaign it like that.guess i have to read the Array chapter again to understand why.
Edit: Figured it out myself.
Should have used something like strcpy(p_candy[0].brand , "japp");
right?
Last edited on
lilysfather wrote:
But i cant assaign it like that.guess i have to read the Array chapter again to understand why.
Edit: Figured it out myself.
Should have used something like strcpy(p_candy[0].brand , "japp");
right?


In C++, the std::string class has an overloaded assignment operator, which essentially has code that copies chars individually from one object to the other.

C has no such concept of operator overloading, so one must use a library function which does the copy of the individual chars.

But really you should think about whether you want to do C code or C++, it is seen as bad style to mix C & C++ code - for example using printf instead of cout, or processing things individually when there is an algorithm that does it for you.

As said earlier std::string has lots of very handy things, as does all of the STL.

HTH


Topic archived. No new replies allowed.