c - sizeof float array, different results, is there any workaround? -
i making function has fixed sized float array input:
char foo(float farr[3]) { } before call function, tested size of float array input.
float farr[3]; int s = sizeof(farr); char result; result = foo(farr); and gives me s=12.
but when tried move checking in function itself:
char foo(float farr[3]) { int s = sizeof(farr); //do } but gives me s=4
i have 2 questions here:
why so?
all want check if user gives float array sufficient size. there way enforce signature of function itself, without additional info caller?
for instance, can make signature having additional info:
char foo(float *farr, int size_farr); then call this
float farr[3]; char result; result = foo(farr, sizeof(farr)); but want avoid that, if possible, using function signature without additional info caller such sizeof(farr).
you cannot have compiler verify size way: char foo(float farr[3]). compiler interprets char foo(float *farr) , ignores number of array elements specified. in body of function, sizeof(farr) evaluates size of pointer, 4 bytes on architecture.
the alternatives mention in question possible, although more idiomatic specify number of elements instead of byte size of array pointed pointer argument. pass information way:
float farr[3]; char result; result = foo(farr, sizeof(farr) / sizeof(farr[0])); in c99, there extended syntax purpose:
char foo(float farr[static 3]) { ... } this specifies farr pointer array of @ least 3 floats. aware sizeof(farr) still size of pointer inside function. here example:
#include <stdio.h> int size(float arr[static 3]) { return sizeof(arr); } int main(void) { float arr1; float arr2[2]; float arr3[3]; float arr4[4]; float *arr2p = arr2; printf("size(arr1) = %d\n", size(&arr1)); printf("size(arr2) = %d\n", size(arr2)); printf("size(arr2p) = %d\n", size(arr2p)); printf("size(arr3) = %d\n", size(arr3)); printf("size(arr4) = %d\n", size(arr4)); return 0; } compiling clang -std=c99 produces these diagnostics:
arrsta.c:4:22: warning: sizeof on array function parameter return size of 'float *' instead of 'float[static 3]' [-wsizeof-array-argument] return sizeof(arr); ^ arrsta.c:3:20: note: declared here int size(float arr[static 3]) { ^ arrsta.c:15:37: warning: array argument small; contains 2 elements, callee requires @ least 3 [-warray-bounds] printf("size(arr2) = %d\n", size(arr2)); ^ ~~~~ arrsta.c:3:20: note: callee declares array parameter static here int size(float arr[static 3]) { ^ ~~~~~~~~~~ 2 warnings generated. as can see, if gives useful warning potential sizeof(arr) confusion , complains if pass array short, not if pass pointer, if pointer not pointing array of sufficient size. imperfect, better nothing.
Comments
Post a Comment