arnuld said:
okay, I have written this. So now I know about both sizeof() and that
arrays can not be passed to functions :
/* A program to understand the output of sizeof operator
*
*/
Overall, it's not a bad demonstration, but I have few comments.
#include <stdio.h>
#include <stdlib.h>
int main()
Ok, but "int main(void)" is preferred.
{
int arr_char, arr_int, arr_LD;
char ac[] = "abc";
int ai[] = { 1, 2, 3};
long double ald[] = { 1.3, 78659.90098, 0.0001 };
/* casting to int because sizeof yields a size_t value */
arr_char = (int) sizeof( ac );
arr_int = (int) sizeof( ai );
arr_LD = (int) sizeof( ald );
The casts are unnecessary. Both size_t and int are integral types;
one will be implicitly converted to the other by the assignment.
The parentheses on the sizeof operators are also unnecessary; they're
needed only when the argument is a type name, or when you need them to
specify grouping. Thus:
arr_char = sizeof ac;
arr_int = sizeof ai;
arr_LD = sizeof ald;
Better yet, since these three variables hold the result of sizeof,
declare them as size_t (or maybe not; see below).
printf("Size of different types of Arrays in BYTES: \n");
printf("\n%d\n", arr_char);
printf("%d\n", arr_int);
printf("%d\n", arr_LD);
Good. Note that if you followed my advice above and declared these as
size_t, you'd need to cast them to int for printf. It's usually best
to declare something of the appropriate type for what it needs to
hold, but in this case using int does simplify the code. There are
always tradeoffs.
arr_char = ( (int) sizeof(ac) / sizeof(char) ) - 1;
arr_int = ( (int) sizeof(ai) / sizeof(int) );
arr_LD = ( (int) sizeof(ald) / sizeof(long double) );
More unnecessary casts and excessive parentheses. And the "- 1" for
arr_char presumably is intended to allow for the trailing '\0' on the
string -- but that '\0' is just as much part of the array as the 'a',
'b', and 'c' are. Your array ac is 4 elements long, not 3.
Note that sizeof(char) is 1 by definition.
And here's a good idiom for computing the length of an array:
arr_char = sizeof ac / sizeof ac[0];
arr_int = sizeof ai / sizeof ai[0];
arr_LD = sizeof ald / sizeof ald[0];
Of course, when using this idiom you have to make sure that the name
(ac, ai, or ald) is actually the name of an array object, not of, say,
a function parameter that's really a pointer.
printf("\nSize of Arrays themselves, number of elements they contain: \n");
printf("\n%d\n", arr_char);
printf("%d\n", arr_int);
printf("%d\n", arr_LD);
return EXIT_SUCCESS;
}
Good. (Note that "return 0;" is equally valid.)
[snip]