开发者

Sizeof C array with integers (in Obj-C)

myclass.h:开发者_如何学C

#define BUTTON_NAVI 41;
#define BUTTON_SETTINGS 42;
#define BUTTON_INFO 43;

myclass.m:

int btnNavi = BUTTON_NAVI;
int btnSettings = BUTTON_SETTINGS;
int btnArray[2] = {btnNavi, btnSettings};
NSLog(@"count = %i", sizeof(btnArray));
[self addToolbarButtons:btnArray];

-> Log: count = 8

8?! What did I do wrong?

And inside "addToolbarButtons" count is 4... :-(

EDIT:

- (void)addToolbarButtons:(int[])buttonIdArray {
    NSLog(@"count = %i", sizeof(buttonIdArray));
}

-> Log: count = 4


sizeof is giving you the size in bytes, 8 bytes sounds right for 2 integers (32-bit or 4 bytes each).

If what you want is the length of the array, you can do sizeof(arr) / sizeof(arr[0]) which will give you the size of the entire array divided by the size of each element. In this case you will get 8 / 4 == 2, which is what I take it you expect.

EDIT To answer your second question, when you pass the array to the method, you're actually passing a pointer to the array. Hence, the size of the pointer is also 32-bits or 4 bytes. If you want the function to know the length of the array, you need to also pass its length along with said pointer.


sizeof is giving the size of the array in bytes. An int is 4 bytes, so a 2-element array of ints will be 8 bytes.

However, sizeof won't do what you want in your method. When a C array is passed into a function (or method), it actually get passed as a pointer, and sizeof will return the size of a pointer. You should modify your method to take a length parameter:

- (void)addToolbarButtons:(int *)buttonIdArray length:(size_t)len
{
    NSLog(@"count = %d", len);
}


The sizeof operator gives you the size in bytes of the thing you pass to it. If an int is 4 bytes, then an array of two ints is 8 bytes.

However, sizeof is a compile-time check on the variable itself. At runtime, the bounds of an array are not known — nor are they known outside the scope where the variable was defined. When you declare the argument (int[])buttonIdArray, the compiler desugars that to (int *)buttonArray — it's just a plain int pointer. So when you do sizeof(buttonArray), it tells you the size of a pointer, 4.

Because the language doesn't keep track of their size for you, using C arrays is a pain. You have to pass the number of elements in the array to every function and method that acts on it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜