To call the function, you must pass the address of the array (just as you would with a struct): The function signature declares that process_array() is expecting a pointer to an array of (exactly!) 10 uint32_t objects. The syntax for passing an array by pointer is a little unwieldy due to C’s precedence rules: Oops.īecause of this it is normal practice to pass an additional parameter, the number of elements in the (supplied) array:Īn alternative (I’m loathe to use the word ‘better’ here) approach is to use the mechanism preferred for all large data types – pass-by-pointer. We’re dividing the size of a pointer by the size of an int. If we re-write the function to the (semantically-identical, remember!) equivalent and expand the macro: In a 32-bit architecture we’ll always get an answer of 1, irrespective of the actual number of elements in the array! However, within our function we may not get the answer we expect: A simple piece of macro programming can yield the number of elements: The sizeof() operator yields the amount of memory an object occupies so for an array this is the number of elements times the size of the element. Once inside our function, very commonly we wish to know the number of elements in the array. What looks like an array name is (of course) just a (non-const) pointer which can be modified, either deliberately or accidently. In the case of a function parameter, though, we could easily delude ourselves: In fact, all these declarations for process_array() are semantically identical the code generated is the same in each case:Ī word of warning here: as we discussed above the array name yields a constant value that is the address of the first element. The array parameter degrades to a pointer – the address of the first element so we could (and many C programmers do) just as legitimately write the following and get the same result: It is not possible to pass an array by-value to a function, so the function process_array() below does not make a copy of the array: When passing arrays to functions (as parameters) things can get a little confusing. The array (‘’) notation is syntactic sugar to hide these details from the programmer: Pointer arithmetic semantics ensure that elements can be accessed as offsets from the array’s base address. As far as the C compiler is concerned an array is merely a contiguous sequence of objects (all of the same type). In C there is a close (if somewhat messy!) relationship between arrays and pointers. This week, it’s the use of arrays as function parameters.Īt first glance the code horrified me (as I’m sure it will horrify some of you out there!) but as I’ve played with it I can see real merit in the technique. I have defined a global array in main.Every so often you pick up a snippet of information that completely changes the way you view things.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |