c - Why do people declare array size sometimes? -
why there need declare array size example: type "array[50]" while type "array[]" still same thing. , have seen other similar things in code
talking arrays in function parameters
in function parameters, it's true int array[] , int array[40] exactly same thing (they both transformed compiler int *); however, i've seen second form being used form of documentation output arrays, show client code @ least how big array expected be.
personally, i'm kind of ambivalent use, since is useful documentation, novices think (1) requirement somehow enforced compiler , (2) sizeof(array) works expected.
talking array definitions
first of all, can int array[] if initializing something, e.g. in
int array[] = { 1, 2, 3, 4, 5}; the compiler doing favor counting elements in initializer , making array big enough; cannot do:
int array[]; /* not compile */ because compiler wouldn't know how big array allocate.
now, people do:
int array[50] = {1, 2, 3}; this can useful because have default value first values, , other initialized zero. done strings:
char buf[256] = "test"; here have buf initialized "test", still have headroom other characters, used if e.g. want concatenate other strings or use full size of buffer in different code paths.
char username[256] = "guest"; if(requirelogin) { printf("please enter name: "); if(!fgets(username, sizeof username, stdin)) exit(1); size_t sz = strlen(username); sz && username[sz-1]=='\n' && username[sz-1]=0; } logcurrentuser(username);
Comments
Post a Comment