Posted By: BobbyT
[SOLVED]-Arrays - get number of slots - 07/14/17 21:24
Looks who's back, back again....
I'm trying to get the length of an array. According to SO posts and C manuals this is achievable using sizeof()
I have got the size of a single array element but the size of the whole array is not retrieved properly. I'm certain I've done this correctly according to C rules but maybe it's different in lite-C? Is there a way to get an array length in lite-C?
Cheers,
BobbyT
EDIT: I have also tried the malloc/free trick (I think) but the values returned are way off. I feel I'm closer but, not by much. Here's the code implementing the use of malloc/free/memory:
I'm trying to get the length of an array. According to SO posts and C manuals this is achievable using sizeof()
I have got the size of a single array element but the size of the whole array is not retrieved properly. I'm certain I've done this correctly according to C rules but maybe it's different in lite-C? Is there a way to get an array length in lite-C?
Code:
void main() { int tfArray[3] = {5,60,1}; //get the size of the whole array int arSize = sizeof(tfArray); //get the size of the first element in the array int arElementSize = sizeof(&tfArray[0]); //get the array length int arLen = sizeof(tfArray)/sizeof(&tfArray[0]); //report what we find printf("nArray size in bytes = %i", arSize); printf("nArray element size in bytes = %i", arElementSize); printf("nArray length = %i", arLen); }
Cheers,
BobbyT
EDIT: I have also tried the malloc/free trick (I think) but the values returned are way off. I feel I'm closer but, not by much. Here's the code implementing the use of malloc/free/memory:
Code:
function main() { int tfArray[3] = {5,60,1}; printf("nMemory before malloc is %i", memory(0)); int array = malloc(tfArray); int mem = memory(0); printf("nMemory after malloc is %i", memory(0)); free(array); printf("nMemory after free is %i", memory(0)); //get the size of the whole array int arSize = mem - memory(0); //get the size of the first element in the array int arElementSize = sizeof(&tfArray[0]); //get the array length int arLen = arSize/sizeof(&tfArray[0]); //report what we find printf("nArray size in bytes = %i", arSize); printf("nArray element size in bytes = %i", arElementSize); printf("nArray length = %i", arLen); }