Reputation: 1501
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
Upvotes: 9
Views: 26239
Reputation: 14523
I was suffering for a long time to convert NSString
to char
to use for this function
-(void)gpSendDTMF:(char) digit callID: (int)cid;
I have tried every answer of this question/many things from Google search but it did not work for me.
Finally I have got the solution.
Solution:
NSString *digit = @"5";
char dtmf;
char buf[2];
sprintf(buf, "%d", [digit integerValue]);
dtmf = buf[0];
Upvotes: 0
Reputation: 2614
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
Upvotes: 3
Reputation: 67831
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);
Upvotes: 1
Reputation: 45398
I think you want to use:
const char *datechar = [date UTF8String];
(note the * in there)
Upvotes: 8
Reputation: 2888
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).
Upvotes: 30