Convert const char* array to char *array

Discussion in 'Mac Programming' started by cea, Feb 4, 2010.

  1. cea macrumors newbie

    Oct 26, 2009

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

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

    char *bytesArray = [data bytes];
    // Convert
    char *charbytesArray bytesArray??????
    anyone can help me?
    Thank you!
  2. chown33 macrumors 604

    Aug 9, 2009
    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.
  3. cea thread starter macrumors newbie

    Oct 26, 2009
    I want to modify bytesArray in bytes (not directly in NSString *aStr) therefore i need to convert it to a char.
  4. robbieduncan Moderator emeritus


    Jul 24, 2002
  5. Sander macrumors 6502

    Apr 24, 2008
    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.
  6. chown33 macrumors 604

    Aug 9, 2009
    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:
  7. jared_kipe macrumors 68030


    Dec 8, 2003
    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.

Share This Page