code doesnt flip array

This is a discussion on code doesnt flip array within the C Programming forums, part of the General Programming Boards category; 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, ...

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    134

    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;
    }

  2. #2
    eh ya hoser, got a beer? stumon's Avatar
    Join Date
    Feb 2003
    Posts
    323
    this compares pointers (addresses).
    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)

  3. #3
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,676
    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

  4. #4
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,386
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. beginner here need help with an array code
    By Ohshtdude in forum C++ Programming
    Replies: 6
    Last Post: 02-01-2009, 04:42 PM
  2. Trimming the fat out of my code for an Array
    By katipo in forum C Programming
    Replies: 17
    Last Post: 12-09-2008, 12:47 PM
  3. Replies: 7
    Last Post: 11-25-2008, 12:50 AM
  4. Code to store PGM file as a workable array
    By InnerCityBlues in forum C++ Programming
    Replies: 4
    Last Post: 11-10-2004, 04:11 PM
  5. Code: An auto expanding array (or how to use gets() safely).
    By anonytmouse in forum Windows Programming
    Replies: 0
    Last Post: 08-10-2004, 12:13 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21