-1
NSString *lang = @"en";    
const char* ar = [lang UTF8String];
int size_of_array = (sizeof ar) / (sizeof ar[0]);

size_of_array is equal to 4 and (sizeof ar) = 4 and sizeof ar[0] = 1. Why? I think it (size_of_array) has to be 2.

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194

2 Answers2

5

sizeof ar will get the size of the type char *, which is a pointer and so takes 4 bytes in memory. You want to get the length of the string, so use the function strlen instead of sizeof ar

Jonathan.
  • 53,997
  • 54
  • 186
  • 290
2

It isn't clear what you are trying to do.

Your third line of code references an array "ar" that isn't declared anywhere in your post, and doesn't seem to relate to the code before it.

Also, the bit sizeof ar[] doesn't make much sense. That will give you the size of a single element in your ar array, whatever that is. So you are taking the size of the pointer variable ar, and dividing it by the size of one element in the ar array.

Are you trying to determine the memory size of the ASCII string lang_ch?

If so, then you want

int size_of_array = strlen(lang_ch) + 1;

That will give you the length of the string you get back, including the null terminator.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Minor remarks: 1) `sizeof(char)` is always one (per definition) - 2) `sizeof` is a keyword, not a function. It requires parentheses when used with a type, but not when used with an expression. Compare http://stackoverflow.com/questions/5894892/why-do-i-need-to-use-parentheses-after-sizeof. – Martin R Jun 14 '14 at 12:12
  • @MartinR, thanks for clarifying the nature of sizeof. I was too lazy to go find my copy of K&R. I know that char is always size 1, but its a good habit to write `count * number_of_elements` type code when calculating the size of dynamically allocated structures, so I was following that pattern. – Duncan C Jun 14 '14 at 12:49
  • "sizeof(char) * lang_ch[0]);" makes less sense than the question's code. First, there's a stray parenthesis. Second, you multiplying the first character value by 1? How does that give the size of an array? You're likely to get 101, the UTF-8 value of "e", the first character of `lang`. – Ken Thomases Jun 14 '14 at 16:15
  • Oh lordy, you're right. I haven't used C strings in so long that I relapsed to PASCAL strings, where the first byte is a length-byte. – Duncan C Jun 14 '14 at 18:51
  • Remove the `[0]`. You're passing a `char` to something expecting `char*` (pointer to `char`). – Ken Thomases Jun 14 '14 at 19:35
  • Good lord. Time to just pack it in on this thread. – Duncan C Jun 14 '14 at 20:21