5 years, 3 months ago.

Length of an array

Hi, i have several arrays defined:

char mynumbers3[] = {123, 102, 255};

char mynumbers1[] = {254}

i want to find the length of the arrays

sizeof(mynumbers1) / sizeof(mynumbers1) returns 4

strlen(mynumbers1) also returns 4

how is this possible?

What's the exact function to return 3 and 1 ?

2 Answers

5 years, 3 months ago.

sizeof(mynumbers3) / sizeof(mynumbers3[0])  
sizeof(mynumbers1) / sizeof(mynumbers1[0])  

Reference: http://stackoverflow.com/questions/1975128/sizeof-an-array-in-the-c-programming-language

and

In the C language, there is no method to determine the size of an unknown array, so the quantity needs to be passed as well as a pointer to the first element.

5 years, 3 months ago.

If you are in the same scope as the array definitions then sizeof(array)/sizeof(array[0]) will work. That will give you the size of the whole array divided by the size of a single element which is equal the number of elements in the array.

However you need to be very careful doing this. e.g.

int myIntArray[] = {100,101,102,103,104};
char myCharArray[] = {100,101,102,103,104};

main () {

  sizeof (myIntArray); // returns 10 on 16 bit systems, 20 on 32 bit systems (5x2 or 5x4 depending)
  sizeof (myIntArray)/sizeof(myIntArray[0]); // returns 5 (10/2 or 20/4 depending on the system)

  sizeof (myCharArray); // returns 5 since a char is only ever 1 byte
  sizeof (myCharArray)/sizeof(myCharArray[0]); // also returns 5 (5 / 1)

  measureSize(myIntArray); // probably returns 1 (size of an int* / size of an int which will normally both be the same size.)

}

int measureSize(int arrayToMeasure[]) {
  return sizeof(arrayToMeasure)/sizeof(arrayToMeasure[0]); // at this point arrayToMeasure is considered an int*
}

Because of these possible complications it's generally a lot safer to also define a constant which tells you the size of the array rather than trying to calculate it in the program. It's safer and faster, the down side is that if you change the array definition you also have to update the constant.

strlen() should only be used for char arrays containing text. It will return the number of bytes until it finds a memory location containing 0 (the c end of string indicator). If you pass it a non-text array then it will give the location of the first 0 in the data. If the data doesn't contain any 0's then it'll keep going past the end of the array counting whatever happens to be next in memory until it finds a location with 0 in.