I am currently taking a c programming class, and have just had the worst time trying to figure out how to properly use pointers and functions. I understand how they work in theory, but I just can't seem to get the syntax down right, which has caused no end to my stress. Please, I need some serious help here.
My teacher has given me a fully written code, and asked me to build three functions to accommodate it. It seems simple in theory, but I can't figure out how to do it. First, I'm passed a 9 length array that I need to reverse (revArray(a)), then I need to return it to its original state (*revElement(a)), and then I need to sort the evens and the odds (evenOdd(a)).
Code:
#include <stdio.h>
#include <stdlib.h>
#define N 9
/* MAIN */
int main()
{
/* Load the array with numbers */
int a[N];
int idx;
int *p = a;
while(p < a + N)
*p++ = a + N - p;
printf("Original: ");
p = a;
while(p < a + N)
printf("%2d ",*p++);
/* Part A: Reverse the array */
revArray(a);
printf("\nReversed: ");
p = a;
while(p < a + N)
printf("%2d ",*p++);
printf("\n");
/* Part B: Return elements in reverse order */
/* printf("Original: ");*/
for (idx = 0; idx < N; idx++)
{
printf("%2d ",*revElement(a));
}
printf("\n");
/* Part C: Put even numbers first, odd numbers last in the array. Order of
the elements is not important as long as all evens are before first odd*/
printf("Even: ");
evenOdd(a);
p = a;
while(p < a + N)
printf("%2d ",*p++);
printf("\n");
return 0;
}
Every time I write a function, it doesn't work at all, so can I tell you what I think I should build as a function, and then you could tell me where I'm mistaken?
For (revArray(a)), I need to make a pointer equal to (a), and then rewrite (a), assigning a [0] = p [N - 1], a [1] = p [N - 2]...a [N] = p [0].
This is what I wrote
Code:
int revArray(int arr)
{
int *p = arr;
for (;p < N; p++)
{
p = arr + N - arr;
}
for (arr = p; arr <N; arr++)
{
arr = p + N - arr;
}
return (arr);
}
I've tried all kinds of different variations, but none work. What am I missing here??
As for (*revElement(a)), I assume I just have to build the same loop as in (revarray), as a[0] will be put back into a[N]. However, as it's a pointer, I'll need to return (&a), not just (a). Is this correct, or am I wrong on that as well?
Finally, for (evenOdd(a)), I assume I can just build an array of N+1, and then use %2, and assign all with an output zero to a++, while those with any other output to a-- + N. I've been so stuck on (revarray) that I haven't even had a chance to write that yet, but does it sound like I'm on the right track?
Again, any help would be massively appreciated.