简体   繁体   中英

how to get the size of the following array

int first[] = {1, 4};
int second[] = {2, 3, 7};

arrayOfCPointers[0] = first;
arrayOfCPointers[1] = second;

NSLog(@"size of %lu", sizeof(arrayOfCPointers[0]) / sizeof(int));

I want to have an array of sub arrays. Each sub array needs to be a different size. But I need to be able to find out the size of each sub array?

The Log keeps returning 1

You need to store the size somewhere. The language does not do so for bare C arrays. All you have is the address of the first element.

I'd write a wrapper class or struct to hold the array and it's metadata (like length).

typedef struct tag_arrayholder
{
    int* pArray;
    int  iLen;
}ArrayHolder;


    int first[] = {1, 4};

    ArrayHolder holderFirst;
    holderFirst.pArray = first;
    holderFirst.iArrayLen = sizeof(first) / sizeof(int);

    arrayOfCPointers[0] = holderFirst;

    NSLog(@"size of %lu", arrayOfCPointers[0].iLen);

Or, like trojanfoe said, store special value marking the last position (exactly the approach zero-terminated string uses)

The "sizeof" instruction could be used to know the amount of bytes used by the array, but it works only with static array, with dynamics one it returns the pointer size. So with static array you could use this formula : sizeof(tab)/sizeof(tab[0]) to know the size of your array because the first part give you the tab size in bytes and the second the size of an element, so the result is your amount of element in your array ! But with a dynamic array the only way is to store the size somewhere or place a "sentinal value" at the end of your array and write a loop which count elements for you !

(Sorry for my English i'm french :/)

The NSLog statement is printing the value 1 because the expression you're using is dividing the size of the first element of the array (which is the size of an int ) by the size of an int .

So what you currently have is this:

NSLog(@"size of %lu", sizeof(arrayOfCPointers[0]) / sizeof(int));

If you remove the array brackets, you'll get the value you're looking for:

NSLog(@"size of %lu", sizeof(arrayOfCPointers) / sizeof(int));

As other answers have pointed out, this won't work if you pass the array to another method or function, since all that's passed in that case is an address. The only reason the above works is because the array's definition is in the local scope, so the compiler can use the type information to compute the size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM