Having trouble finding the length of an array in C?

I am trying to find the cache block by keeping a huge block of 16 MiB and by trying to access different elements each time to find the time. I just can't write the length of the array.

How can I write a for loop to iterate over the array. I need the length of the array; how can I find that? I have tried sizeof(a)/sizeof(a[0]) but this doesn't work or I am doing something wrong because my assignment sheet tells me it can hold 4 million int's..

register *a;

a = malloc(16777216);

int i;

for (i = 0; i < sizeof(a)/sizeof(a[0]); i = i + 1) {

printf("\ni = %d", i);

}

This only prints i = 0 i = 1.

网友答案:

The code sizeof(a) simply returns the size of the pointer register *a, and is completely unrelated to the size of the array that a points to.

C arrays do not track how many items they contain. You can use this syntax only if the size of the array is known at compile time. But you can't do it with an array allocated this way.

For this task, you'll need to track this information yourself. You can store that value in a variable, or you could append an array element with a special value that indicates it's the end of the array (much like we do with C strings).

网友答案:

a is a register pointer an not an array. so sizeof(a) will not return 16MB as you are expecting. please use 16777216 directly instead of sizeof()