0

I'm trying to calculate the length of an array using the sizeof() function in C language. The following is my code.

Code

#include <stdio.h>

void printArraySize(int array[]);

int main() {
    int array[] = {1, 2, 3, 4, 5, 6};
    int size = sizeof(array) / sizeof(array[0]);
    printf("Size of array - %d\n", size);
    printArraySize(array);

    return 0;
}

void printArraySize(int array[]) {
    int size = sizeof(array) / sizeof(array[0]);
    printf("Size of array - %d\n", size);
}

When I'm calculating the length of the array inside the main function, the output is correct. But when I try to do the same inside the function printArraySize() which accepts an integer array, the output is always 1.

I'm new to C language and I'm getting so confused with this. Can anyone please explain to me the reason behind the same and also suggest the code which can calculate the length of an array inside a function.

Thank you

Vaibhav
  • 562
  • 5
  • 12

2 Answers2

4

You get that behaviour because, in the C language the function declaration

void printArraySize(int array[])

is equivalent to

void printArraySize(int *array)

And therefore the value of the line int size = sizeof(array) / sizeof(array[0]); on a program compiled for 32-bit where sizeof(int) == 4 is always 1.

Arrays cannot be passed to functions as arrays, but as pointers. In fact, if you try to modify array in the printArraySize function you will modify it also in the caller function main.

And that's why strings in C (and in many other programming languages) are 0-terminated.

LuxGiammi
  • 631
  • 6
  • 20
  • 1
    Okay. Now the things are getting clearer. Thanks for clearing the doubt. One more question. Since a pointer is getting passed to the function, the sizeof() method will return the size of the pointer, right? – Vaibhav Jan 10 '21 at 16:11
  • 1
    @Vaibhav Yes. And that's why I supposed you're using a 32 bit compiler with 4-bytes `int` (or you might be using a 64 bit compiler with 8 bytes `int`). – LuxGiammi Jan 10 '21 at 16:13
0

This bit

 void printArraySize(int array[]) {

could be wrote as

 void printArraySize(int* array) {

So it both cases they act as a pointer,

So,

sizeof(array)

in The function printArraySize would return the size of a pointer, not the array as expects.

You should not does not array its size outside the compiler

Ed Heal
  • 59,252
  • 17
  • 87
  • 127