If the array is a global, static, or automatic variable (
int array[10];
), then sizeof(array)/sizeof(array[0])
worksIf it is a dynamically allocated array (
Note that
Code:
int main()
{
size_t count=sizeof(int) * BITS_PER_BYTE * sizeof(char);
char *str=(char*)malloc(count);
printf(" The size is %d\n",count);
memset (str,0,count);
getchar();
return 0;
}
int* array = malloc(sizeof(int)*10);
or void f(int array[])
), then you cannot find its size at run-time. You will have to store the size somewhere as explained in the code.Note that
sizeof(array)/sizeof(array[0])
compiles just fine even for the second case, but it will silently produce the wrong result.Code:
int main()
{
size_t count=sizeof(int) * BITS_PER_BYTE * sizeof(char);
char *str=(char*)malloc(count);
printf(" The size is %d\n",count);
memset (str,0,count);
getchar();
return 0;
}
No comments:
Post a Comment