You can use memcpy()
or strcpy()
, but you'll have to do the bounds checking yourself and there are other errors in your code.
So, I take it you want to copy an NSString into a char[16]
array. You can use an NSString
builtin method to do this, and you don't have to use memcpy()
yourself:
NSString *src;
char dest[16];
NSUinteger destlen;
[src getBytes:dest
maxLength:sizeof(dest) - 1
usedLength:&destlen
encoding:NSUTF8StringEncoding
options:0
range:NSMakeRange(0, [src length])
remainingRange:NULL];
dest[destlen] = '\0';
If you want to use memcpy()
, then you'll have to do it this way:
NSString *src;
char dest[16], *srcUtf8;
size_t len;
srcUtf8 = [src UTF8String];
len = strlen(srcUtf8);
if (len >= sizeof(dest))
len = sizeof(dest) - 1;
memcpy(dest, srcUtf8, len);
dest[len] = '\0';
Errors in your code
This code has two errors in it!
memcpy(&profile.friendly_name, &string, 16); // Wrong!
First of all, &string
is wrong. It should be string
, because string
is a pointer to the string data you want to copy. If you copy &string
, you will get a pointer and some random bits of stack data copied instead. In other words, you'll get garbage.
Secondly, 16 is wrong. You can only copy 16 bytes if you know that string
points to at least 16 bytes of data. This will cause a segmentation fault (crash your program, hard) if string
is less than 16 bytes the following data in memory is not readable. It might not crash today, but maybe it will crash next week, and you'll have forgotten all about it?
It's wrong, don't pass 16 unless you know the source is at least 16 bytes long.