I am trying to understand exactly what this code is trying to accomplish. The function median was given, but I added the main function and typedef/prototypes in efforts to comprehend what it does, by passing something into the function. However I can figure out what or how to pass something to it. I understand that the function is some kind of sort. What I really need to know is what is exactly being passed to the function? An array of N index?
Thank you for any guidance!
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char pix_t;
pix_t median(pix_t window[N]);
int main() {
pix_t window[] = { 4, 3, 2, 1 };
pix_t output;
output = median(window[N]);
}
pix_t median(pix_t window[N])
{
pix_t t[N], z[N];
int ii, k, stage;
// copy locally
for (ii = 0; ii<N; ii++) z[ii] = window[ii];
for (stage = 1; stage <= N; stage++) {
k = (stage % 2 == 1) ? 0 : 1;
for (ii = k; ii<N - 1; ii++) {
t[ii] = MIN(z[ii], z[ii + 1]);
t[ii + 1] = MAX(z[ii], z[ii + 1]);
z[ii] = t[ii];
z[ii + 1] = t[ii + 1];
}
}
return z[N / 2];
}
Given the function signature
pix_t median(pix_t window[N])
a call like
median(window[N]);
is wrong. The function expects an array of pix_t
with at least N
elements Note, whereas, you're passing only a single variable of type pix_t
.
Morale of the story:: Whenever in confusion, check the data types
The function should be called with an array, something like
#define N 10 //any number
int main(void) { //note the change
pix_t window[N] = { 4, 3, 2, 1 };
pix_t output;
output = median(window); //passing the array
}
should do.
Point to note: despite the array notation used in the function signature
pix_t median(pix_t window[N]) { //....
inside the function, window
is not an array. Quoting C11
, chapter §6.7.6.3
A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the
[
and]
of the array type derivation. [....]
Note:
What I really need to know is what is exactly being passed to the function? An array of
N
index?
The meaning of "at least N elements" refers to the a guarantee that the array has enough storage space to hold N
elements up to position N-1
, not that indices N
, N+1
, N+2
, ...
are valid/addressable.
You can read it as: "I have a guarantee of at least N
cells of storage space so that I can store at most N
elements in N-1
valid positions."
However, it's the programmer's responsibility to keep track of these details manually to avoid indexing into an invalid location and causing a segmentation fault; the environment will not do this automatically for you.