Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting a NSString to char problem

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

like image 370
issac Avatar asked Feb 26 '09 08:02

issac


4 Answers

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).

like image 162
Joel Levin Avatar answered Nov 12 '22 20:11

Joel Levin


I think you want to use:

const char *datechar = [date UTF8String];

(note the * in there)

like image 28
Marc Novakowski Avatar answered Nov 12 '22 22:11

Marc Novakowski


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

like image 20
Heider Sati Avatar answered Nov 12 '22 20:11

Heider Sati


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);
like image 1
mouviciel Avatar answered Nov 12 '22 20:11

mouviciel