TIL: Passing arrays to functions in c
published
last modified
3kb
To define an array in c
we can do things like:
and so forth. We also know that arrays are really just pointers to the first element in the array (kind of). For example, 'K'
and 1
in the previous examples.
Arrays As Parameters To Functions
We can pass in an array to a function, such as this one that prints the letters of a name:
This works because all c
style strings have the null terminating character \0
at the end of the array of characters. In practice the array name
actually looks like {'K', 'o', 's', 't', 'y', 'a', '\0'}
.
This is why: while(*name)
works. Because once we reach the end and dereference \0
(which is the integer 0 in ASCII) the while loopbreaks because false
is 0
by definition.
We could also write
which is the same but more explicit. But what about nums
?
What Is The Size of The Array?
We know that arrays are just pointers to the first element. So when we define the parameters to an array we can just write:
Thinking in this way, when we pass in the array (pointer) to the function, we lose any notion of the size of the array because we can access elements outside of it. How do we know when to stop the function?
Size or Terminating Element
We really have two options:
- The programmer and users can decide on a null terminating value such as
-1
which will mark the end of the array.
- You can pass in the size of the array to the function beforehand.
Each have their pros and cons.
But TIL that mostly, you have to either pass in the size to a function that loops over an array as a parameter, or agree on a terminal value.
Contact
If you have any comments or thoughts you can reach me at any of the places below.