Question:
Array question for C?
Steve
2010-06-20 01:14:24 UTC
My professor came out this question, and I have no clue, anyone know how to do?

Question:

Name your function reverse. The function reverse must be able to handle an array of any size. Do NOT assume an array of specified limited size will be passed to the reverse function. The main function is the test driver. In main, print the array, then call the reverse function, then print the array again in main, to show it has been reversed.

Test your function with two arrays

2 4 6 8 10

1 2 3 4 5 6
Three answers:
cja
2010-06-20 06:44:07 UTC
Your reverse function takes a pointer to the array, which is reversed in place. Don't think of passing the entire array to the function, then needing the function to pass the array back to the caller. Here's one way to do it:



#include

#include

#include



void reverse(int *, int *);

void displayArray(const char *,const int *, size_t);



int a1[] = { 2, 4, 6, 8, 10 };

int a2[] = { 1, 2, 3, 4, 5, 6 };



int main(int argc, char *argv[]) {

   size_t a1Len = sizeof(a1) / sizeof(int);

   size_t a2Len = sizeof(a2) / sizeof(int);

   int *a = malloc(sizeof(a1));



   memcpy(a,a1,sizeof(a1));

   displayArray("a1 : ",a,a1Len);

   reverse(a,a + a1Len - 1);

   displayArray("reversed: ",a,a1Len);

   a = realloc(a,sizeof(a2));

   memcpy(a,a2,sizeof(a2));

   displayArray("a2 : ",a,a2Len);

   reverse(a,a + a2Len - 1);

   displayArray("reversed: ",a,a2Len);

      

   free(a);

   return 0;

}



void reverse(int *begin, int *end) {

   int temp;



   while (end > begin) {

      temp = *begin;

      *begin++ = *end;

      *end-- = temp;

   }

}



void displayArray(const char *s, const int *a, size_t len) {

   size_t i;



   printf("%s",s);

   for (i = 0; i < len; i++) {

      printf("%3d ",a[i]);

   }

   puts("");

}



#if 0



Program output:



a1 : 2 4 6 8 10

reversed: 10 8 6 4 2

a2 : 1 2 3 4 5 6

reversed: 6 5 4 3 2 1



#endif
IAmBored
2010-06-20 02:34:45 UTC
Umm well, you do need a way to specify when the array ends... maybe something like:



void reverse(int v[], int n){

int i,tmp;

for (i=0;i
tmp=v[n-i-1];

v[n-i-1]=v[i];

v[i]=tmp;

}

}



It should work for any int array with any values of n... I guess that's what your professor wanted...
tbshmkr
2010-06-20 06:11:10 UTC
Reverse Function [C]

=

void reverse(int list[],int j)

{

int i,temp;

j--;

for(i=0;i<(j/2);i++)

{

temp=list[i];

list[i]=list[j];

list[j]=temp;

j--;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...