Convert const char* array to char *array

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

  1. cea macrumors newbie

    Joined:
    Oct 26, 2009
    #1
    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!
     
  2. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #2
    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

    Joined:
    Oct 26, 2009
    #3
    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

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
  5. Sander macrumors 6502

    Joined:
    Apr 24, 2008
    #5
    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

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

    jared_kipe

    Joined:
    Dec 8, 2003
    Location:
    Seattle
    #7
    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