...
| Code Block | ||
|---|---|---|
| ||
void clear(int array[], size_t sizelen) { size_t i; for (i = 0; i < sizelen; i++) { array[i] = 0; } } void dowork(void) { int dis[12]; clear(dis, sizeof(dis) / sizeof(dis[0])); /* ... */ } |
...
In this noncompliant code example, the sizeof a does not equal 100 * sizeof(int). This is because the sizeof operator, when applied to a parameter declared to have array or function type, yields the size of the adjusted (pointer) type, even if the parameter declaration specifies a length.
| Code Block | ||
|---|---|---|
| ||
enum {ARR_LEN = 100}; void clear(int a[100ARR_LEN]) { memset(a, 0, sizeof (a)); /* error */ } int main(void) { int b[100ARR_LEN]; clear(b); assert(b[50ARR_LEN / 2]==0); /* may fail */ return 0; } |
...
In this compliant solution, the size is specified using the expression 100 len * sizeof(int).
| Code Block | ||
|---|---|---|
| ||
enum {ARR_LEN = 100}; void clear(int a[100], size_t len) { memset(a, 0, 100len * sizeof(int)); } int main(void) { int b[100ARR_LEN]; clear(b, ARR_LEN); assert(b[50ARR_LEN / 2]==0); /* cannot fail */ return 0; } |
...