Question:
Reverse order of Array with Pointers, C Programming?
Lauren
2014-11-29 11:19:27 UTC
Write a program that creates integer array with size 5 and assign 1, 2, 3, 4, 5 to the array initially. Then, define
pointer p which directs to the first element of the array. Now, change the order of the array USING pointer p
as describes below and show the changed array as a result.

Original order: 1,2,3,4,5
Output order: 5,4,3,2,1

I believe you should implement a selection sort. however, I am directed to only use one function, a main function. and use temp variable to switch the order.

all i have so far is:

#include

int main(void) {
int array[5]={1,2,3,4,5};
int *p=array;


}
Six answers:
anonymous
2017-01-21 13:21:47 UTC
1
Cristian
2014-11-29 11:37:30 UTC
So you have created an array, and then made an integer pointer that points to the array, so far so good yeah?



You could use a for loop from i = 0, to i < 3. (you only want to go halfway through the array to swap)

Then say, set temp = array[i] and set array[i] = array[4-i] //note you only go to 2, so this last swap is just setting temp to array[2] and then setting array[2] to array [2]. So you really only need to swap elements 0, and 1.



Also didn't add this above but after setting array[i] = array[4-i] you need to set array[4-i] = temp.
?
2016-10-31 16:28:34 UTC
C Reverse Array
anonymous
2014-11-29 11:28:31 UTC
I'd guess you'd use the pointer with an index to, first copy the number the first element to your temp variable, then copy the number in the last array element to the first element. then do the same for second and fourth elements. Then you'd be done.
?
2014-11-29 12:03:32 UTC
you just have to remember that *(a+b) is EXACTLY the same as a[b] it is even parsed that way ( so that a[b] is the same as b[a] *(a+b) is the same as *(b+a) )



#include

void revarr(int *);

int main(void){

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

int j;

revarr(arr);

for(j=0;j<5;j++)

printf("%d ",*(arr+j));

return 0;

}

void revarr(int * a){

int k,t,j;

j=4;

for(k=0;k
t=*(a+k) ;

*(a+k)=*(a+j);

*(a+j)=t;

}

return;

}
anonymous
2014-11-29 11:51:02 UTC
Here is one way, not the best, but it should work for you.



int main(void)

{

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

int *p;

int temp_variable, index, new_index;



p = group;



for(index = 0; index < 5; index++)

printf("%2d\t",group[index]);

printf("\n");



for(index = 0, new_index = 4; index < 3; index++, new_index--)

{

temp_variable = group[index];

group[index] = *(p+new_index);

*(p+new_index) = temp_variable;

}



for(index = 0; index < 5; index++)

printf("%2d\t",group[index]);

printf("\n");



return 0;

}


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