-
code doesnt flip array
why doesnt this code flip the array and print the result??
Code:
#include<stdio.h>
#include<stdlib.h>
main()
{
int b[5]={10,20,30,40,50};
int *frontp, *backp;
int hold;
int i;
for(i=0;i<5;i++)printf("%d^",b[i]);
frontp=&b[0];
backp=&b[4];
while(frontp < backp)
{
hold=*frontp;
*frontp=*backp;
*backp=hold;
frontp=&b[1];
backp=&b[3];
}
for(i=0;i<5;i++)printf("%d^",b[i]);
return 0;
}
-
this compares pointers (addresses).
Quote:
while(frontp < backp)
this will not always return the right results. you want to compare whats being pointed to, like this:
Code:
while(*frontp < *backp)
-
This is basically what your code is doing:
Code:
int front = 0;
int back = 4;
while (front < back)
{
...
front = 1;
back = 3;
}
You can use ++ and -- to move a pointer to the next/previous element in an array. (ie frontp++ backp--)
Do that and your loop will work, and on any size array.
gg
-
You don't need pointers to flip the array, much easier would be to use just the index. The first element is 0, the last element is N-1. The second element is 1, the element to switch with is N-2. Etc. Or use two index variables and let one start at 0 and the other at N-1.