-3
#include <stdio.h>
#include <string.h>

int fashion (int[]);
main()
{   
    int a[]={3,2,5,1,3};

    int size;
    size= sizeof a/sizeof (int);

    printf("size of array %d\n",sizeof(a)); //size of the array
    printf("size of int %d\n",sizeof(int)); //size of the int
    printf("lenght of array %d\n",size);    //actual length of the array
    fashion(a);

    return 0;
}   
int fashion(int input1[])  //tried with int fashion(int *input1)
{
    int size;
    size= sizeof input1/sizeof (int);

    printf("\nin function\n");
    printf("size of array %d\n",sizeof(input1)); //size of the array
    printf("size of int %d\n",sizeof(int)); //size of the int
    printf("lenght of array %d\n",size);    //actual length of the array

}

Below is the output of the code:

output is
size of array 20
size of int 4
lenght of array 5

In function
size of array 8
size of int 4
lenght of array 2

Both the code in main function and function called are same but resulting different results.

Why the size of the array is changed in main function it is 20 and in the function it is 8? who can i make both the results same?

I even tried with Fashion(int input1[]) but resulting in same.

Napster
  • 69
  • 11

1 Answers1

0

This has to do with different typing. sizeof is a compiler operator, not a runtime function.

a is of type int[5], which correctly leads to a size of 5*4 = 20.

input1 is of type int * which has the same size as a void *. sizeof(int *) = sizeof(void *) is normally 4 on on 32-bit systems and 8 on 64-bit systems (which yours seems to be).

Generally when passing arrays to functions you pass the pointer to the first element (as in your function) and additionally the length of the array as a separate argument.

Sergey L.
  • 21,822
  • 5
  • 49
  • 75
  • "sizeof is a compiler operator, not a runtime function" - except when used in VLAs, of course. - "you hard code the array size in your function `int fashion(int input1[5])`" - that's no good either. It will be equivalent with `int fashion(int *input1)` too, and `sizeof` will yield `sizeof(int *)`. –  Jun 21 '13 at 10:46
  • then what could be the solution, i checked the similar problems but unable to correct it, please suggest, other then passing the length separately – Napster Jun 21 '13 at 12:09
  • @Napster Arrays in C do not store the array length. They are technically only pointers to the first element. If you do not want to pass the array length as a separate argument then you have to fix it at compile time with a macro `#define my_array_length 5`, a global variable or by using a fixed length struct `struct my_array_with_5_ints { int values[5]; }` – Sergey L. Jun 21 '13 at 12:37
  • Thanks @H2C03 for the feed back, i got to know the concept now. – Napster Jun 26 '13 at 12:12