Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

cea

macrumors newbie
Original poster
Oct 26, 2009
22
0
Hello,

I want to convert a const char* bytesArray to char *bytesArray

PHP:
NSString *aStr = @"abcde";
NSData *data = [aStr dataUsingEncoding:NSASCIIStringEncoding];

const char *bytesArray = [data bytes];
// Convert
char *charbytesArray = bytesArray??????
anyone can help me?
Thank you!
 
1. Why do you want to do this conversion, which discards const-ness? Do you understand why it's const in the first place, and what ignoring that will do?

2. To answer your question, how would you normally convert a pointer to one type, into a pointer to another type? For example, convert a pointer to float into a pointer to char.
 
I want to modify bytesArray in bytes (not directly in NSString *aStr) therefore i need to convert it to a char.
 
I want to modify bytesArray in bytes (not directly in NSString *aStr) therefore i need to convert it to a char.

Then you need to look into doing things differently. When you are returned a const pointer, you are simply not supposed to change what it points to. Regardless of any clever casting tricks to get the compiler to look the other way when you do your evil deed.

The only reason to cast away const-ness is when passing a pointer to a (legacy) function which you know is not going to change the data, but which didn't advertize so by putting const in its declaration.
 
I want to modify bytesArray in bytes (not directly in NSString *aStr) therefore i need to convert it to a char.

You aren't allowed to modify the bytes in the memory returned by the bytes method. Instances of the NSData class are immutable, and bytes returns an internal pointer. That's what const means: do not modify.

If you want to modify the bytes, then you should copy them into a memory location you are allowed to modify, and modify them there. See the getBytes:length: method of NSData:

http://developer.apple.com/mac/libr...//apple_ref/occ/instm/NSData/getBytes:length:
 
NSString already has methods that return (const char *) Such as - UTF8String and - cStringUsingEncoding:

I don't see the point of the NSData object as an intermediary.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.