Jump to content
  • Advertisement
Sign in to follow this  
Chett2001

char* and char[]'s

This topic is 4063 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

This code should speak for itself:
char cCurrentBook[50];
char* bookName;

cCurrentBook = bookName;
it doesnt work and gives the error:
.\main.cpp(3463) : error C2440: '=' : cannot convert from 'char *' to 'char'
Whats the difference between a char* and a char[] and whats the best way of doing the above?

Share this post


Link to post
Share on other sites
Advertisement
i think the general rule is an l-value cannot be an array type. it works the other way around though. in other words, a pointer is a variable, an array is not. oh yeah, if you want to do what you want to do you can copy the contents using memmove or strcpy or whatever, or use std::string he he he.

bookName = cCurrentBook;

Share this post


Link to post
Share on other sites
I thought i needed a char[] array to do an if comparison but i didnt but im still haveing problems.

I have this if statement:

if(cBookmarkInfo[4]==cCurrentBookName)
{
do this..
}

both are equal to "book.txt" but the if statement isnt firing, is there a reason for this? cant you do a comparison like this?

Share this post


Link to post
Share on other sites
cCurrentBookName is a pointer to char. Nothing more.

Such comparison would only compare whether they are pointing to the same location, it doesn't compare the contents.

In addition, cCurrentBookName doesn't specify number of elements. There doesn't even need to be a number of elemnts, since you can do (char *)(&WhateverType).

For comparison of types you'll need to specify the length as well.

One way to compare would be:
bool str_equals( char *a, char *b );


Here you'd assume that a and b are null terminated char arrays. Whether this is true depends only on the god you pray to.

Better way is:
bool str_equals( char *a, int la, char *b, int lb)

Here, la and lb are lengths of arrays or length of strings. Each has its pros and cons. One guards agains overruns, other makes it easier to compare.

If this is C, then there's standard API for string comparison, such as strcmp.

Finally, if you're working in C++, all of that is moot point, since there's std::string which takes care of all of that. And by the time you do need raw char arrays, you won't have such problems anymore.

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!