-3
#include<stdio.h>
void func(int x[]);
main()
{
    int a[]={1,2,3,4};
    printf("size of %d \n",sizeof(a));  // Some value I'm getting
    func(a);
}
void func(int a[]) 
{
    printf("size of %d",sizeof(a));  // Value is changing
}

Both times, the value of 'a' is not printing the same. To get the same value by maintaining this code, what more code need to be added or any changes required?

I don't want to change the signature of any function. Without changing the signature, what extra code is needed to be added inside func(int a[])?.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

4

An array function argument decays to a pointer, meaning that the argument to func is of type int*. You can therefore only calculate sizeof(int*) inside func.

If you want to pass the array size, you can either pass it as a separate argument

func(a, sizeof(a)/sizeof(a[0]));
....
void func(int* a, int num_elems);

or initialise a to include a sentinel value marking the array end and iterate through elements until you find that value in func.

simonc
  • 41,632
  • 12
  • 85
  • 103
  • Hi, I dont want to change the signature of any function. please say me without changing the signature what extra code need to be added inside func(). – nitesh saha Apr 20 '13 at 13:43
  • The most common approach would be to change the function signature. If you really can't do this (say because its a restriction on a homework assignment), you'd have to try the sentinel value approach mentioned in the second part of my answer. Choose a value that'll never normally appear in the array and set the last value to this. `func` can then iterate over array elements until it finds one with this sentinel value. Note that all array elements must be initialised before calling `func` for this to work reliably. – simonc Apr 20 '13 at 19:01