i want to casting my NSString to a constant char the code is shown below :
NSString *date = @"12/9/2009";
char datechar = [date UTF8String]
NSLog(@"%@",datechar);
however it return the warning assignment makes integer from pointer without a cast and cannot print the char properly,can somebody tell me what is the problem
Try something more like this:
NSString* date = @"12/9/2009";
char* datechar = [date UTF8String];
NSLog(@"%s", datechar);
You need to use char* instead of char, and you have to print C strings using %s not %@ (%@ is for objective-c id types only).
I think you want to use:
const char *datechar = [date UTF8String];
(note the * in there)
Your code has 2 problems:
1) "char datechar..." is a single-character, which would only hold one char / byte, and wouldn't hold the whole array that you are producing from your date/string object. Therefore, your line should have a (*) in-front of the variable to store multi characters rather than just the one.
2) After the above fix, you would still get a warning about (char *) vs (const char *), therefore, you would need to "cast" since they are technically the same results. Change the line of:
char datechar = [date UTF8String];
into
char *datechar = (char *)[date UTF8String];
Notice (char *) after the = sign, tells the compiler that the expression would return a (char *) as opposed to it's default (const char *).
I know you have already marked the answer earlier however, I thought I could contribute to explain the issues and how to fix in more details.
I hope this helps.
Kind Regards Heider
I would add a * between char and datechar (and a %s instead of a %@):
NSString *date=@"12/9/2009"; char * datechar=[date UTF8String];
NSLog(@"%s",datechar);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With