lundi 29 juin 2015

why can't I print the size of the array inside the function where it's passed in C? [duplicate]


This question already has an answer here:

I have this code where I pass a 1-d array to a function, and try and print it. However, I am not able to print the size of the array inside the function where it's passed.

#include <stdio.h>

int main(void)
{
 int a[] = {1,2,3,4,5,6,7};

 /* works */
 printf("size of a==%d\n",sizeof(a));

 fun(a);

 return 0;
}

int fun(int a[])
{
 int i = 0;

 /* does not work */
 printf("size of a==%d\n",sizeof(a));
 for(i=0;i<(sizeof(a)/sizeof(int));i++)
  printf("%d ",a[i]);

 /* works */
 for(i=0;i<10;i++)
  printf("%d ",a[i]);
}

EDIT: How can I calculate the number of elements in the array if I don't want to pass the number of elements as another argument say,

fun(a, sizeof(a)/sizeof(int));

and receive as

int fun(int a[], int n)
{

}


Aucun commentaire:

Enregistrer un commentaire