You should not use #defines or const variables to represent the size of an array; better to make them explicit.
Instead:
#define TYPICAL_ARRAY_SIZE 4711 int fill_with_zeroes(char *array) { memset(array, 0, TYPICAL_ARRAY_SIZE); } int main(void) { char *za; if((za = malloc(TYPICAL_ARRAY_SIZE)) != NULL) { fill_with_zeroes(za); } }
which uses (generic, imagine in a generic header or something else) #define to tell the size of an array it is much better to simply pass it to the function as a valid argument:
void fill_with_zeroes(char *array, size_t num_elements) { memset(array, 0, num_elements); }
Then just change the call site:
int main(void) { const size_t array_size = 4711; char *za; if((za = malloc(array_size)) != NULL) { fill_with_zeroes(za, array_size); } }
This makes the size local in the place where it was allocated; there is no need for the called function to magically βknowβ something about its arguments, which are not passed through its arguments.
If the array is not dynamically allocated, we can do even better and remove the repeated symbolic size even locally:
int main(void) { char array[42]; fill_with_zeroes(array, sizeof array / sizeof *array); }
Here, the well-known expression sizeof x / sizeof *x used to (at compile time) calculate the number of elements in an array.
source share