Structures

I'm having trouble understanding why this will not compile. It is very simple but I can't seem to see whats wrong.
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
#include<iostream>
using namespace std;

#define LENGTH 26

struct MovieData
{
	char title[LENGTH];
	char director[LENGTH];
	int release;
	int time;
	float costs;
	float revenues;
};

int main()
{
	MovieData myMovie;
	myMovie.title = "Movie Title";
	myMovie.release = 1996;
	myMovie.time = 110;
	myMovie.costs = 1000000;
	myMovie.revenues = 5000000;
	return 0;
}


The problem is in the line myMovie.title = "Movie Title";
The error message is saying, error C2440: '=' : cannot convert from 'const char [12]' to 'char [26]'

I have seen this problem with new C++ programmer's.

In C++ this thing is taken care by the class operator's but here its C and is a raw pointer. It is not going to copy the string in it automatically. You will have to call a function which will do this for you. do it like this:

strcpy(myMovie.title, "Movie Title");
I think you can only do that if title were char *title. I suggest that you use strcpy_s() to copy the string:

strcpy_s(myMovie.title, LENGTH, "Movie Title");

webJose

This is Microsoft specific and will not work if someone is doing coding only on unix like systems.
Really?? LOL! I never noticed that! I am sooo used to use them that I rarely ever notice. So that one belongs to the CRT for Windows? Interesting. What would be the generic alternative? memcpy()?
Thanks for the help. That fixed the problem.

yes, memcopy, memmove functions. All these have a secure version for windows with a _s.
Ok, I have read a little bit about this. It seems that the _s functions from Microsoft are quite controversial in the portable code arena. I also read about strncpy(), which does seem to be part of the standard C library. Use strncpy() instead of strcpy_s(), but make sure that your 26 characters can hold the string and the ending null char, because you only get the null char if your buffer length exceeds the source string's length.

these c library functions don't check for array bounds and hence its the responsibility of the programmer to handle this otherwise there would be security holes in the application like stack smashing.
Topic archived. No new replies allowed.