Jump to content
  • Advertisement
Sign in to follow this  
dxFoo

Problem with C string arrays

This topic is 4856 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm not sure what I'm doing wrong here. It says... error C2440: '=' : cannot convert from 'char [13]' to 'char [80]' I thought str[3][80] would give it plenty of space, but just set a null zero at the end of the given string?
int main(void)
{  
	char str[3][80];

	str[0] = "Hello World!";
	str[1] = "Testing crazily.";
	str[2] = "Testing again.";

	printf("%s", str[rand()%3]);

	return 0;
} 

Share this post


Link to post
Share on other sites
Advertisement
well that's because there's no assignemnt operator for char arrays, you could use a typedef to force the compiler to do it or use strcat, but if you're using c++ be smart about it and use std::string.

Share this post


Link to post
Share on other sites
Arrays of characters do not support operator= for assignment. If this is C, you could use the strcpy() or strncpy() if your compiler has it. If this is C++, consider using std::string instead of char arrays.

Share this post


Link to post
Share on other sites
#include <stdio.h>

int main(void)
{
char str[3][80]={"Hello World!", "Testing crazily.", "Testing again."};

printf("%s %s %s", str[0], str[1], str[2]);

return 0;
}

Share this post


Link to post
Share on other sites
That's from a book?? I guess it worked for the author because char[]s can be down-casted to char*s when they need to be. So the code wasn't copying anything, it was just reseating the pointer. But this isn't great code. Your compiler is being a lot more safe than whatever compiler the author used.

Anyway if you change the declaration to " char* [3] ", then it will work as the guy intended.

Also, what book is this?

Share this post


Link to post
Share on other sites
He mentioned part of what I was experimenting on. I figured it would work but I guess not. Anyway, I gotta run to an interview. Thanks for the help.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!