Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I get: returning const char * from a function with result type char * discards qualifiers

I need te return an NSString as char *:

char *inboxPath (void) 
{ 
    NSURL * url = [[[[NSFileManager defaultManager] 
                 URLsForDirectory:NSDocumentDirectory 
                 inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"inbox.txt"];
    return [[NSString stringWithFormat:@"%@", url] UTF8String]; 
}

I get: Returning 'const char *' from a function with result type 'char *' discards qualifiers

Why I get this and how I can solve it?
Obviously I don't know much C, is there an easier way to do this?

like image 207
Ali Avatar asked Sep 02 '25 09:09

Ali


1 Answers

The function:

char* inboxPath (void);

returns char* while -[NSString UTF8String] returns const char*. The qualifier you're dropping is the const. To solve this, you should declare your function:

const char* inboxPath (void);

Mutating immutable (const) data is one common way to introduce undefined behaviour, so you definitely want to avoid dropping the const qualifier.

If you need a mutable char buffer, make a copy of the utf8 string returned by -[NSString UTF8String].

like image 147
justin Avatar answered Sep 04 '25 22:09

justin