Sign in to follow this  

char* and char[]'s

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

This topic is 3851 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this