Thread: I Need Help With Some Code Involving Pointers.

  1. #1
    Registered User
    Join Date
    Mar 2020
    Posts
    3

    I Need Help With Some Code Involving Pointers.

    Hey,

    This is one of the tasks I have been given in a practical:

    "Create a file called order.c (and its associated header file).Inside, create a static function called ascending2() that takes two int pointers andreturns void. The function should place the smaller of the two int values in the firstmemory location and the larger in the second.In other words, ascending2() should swap its parameters if the first is larger than thesecond, but do nothing otherwise."

    My code compiles although the 2 values (inputed by the user) still swap places in memory even when the first value inputed is already smaller than the second.

    Here's the code:

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    void ascending2(int *i, int *j);
    
    int main(void)
    {
    
      int valueOne;
      int valueTwo;
    
      printf("enter 2 numbers\n");
      scanf("%d %d", &valueOne, &valueTwo);
    
      ascending2(&valueOne, &valueTwo);
    
      printf("%d, %d\n", valueOne, valueTwo);
      return 0;
    
    }
    
    void ascending2(int *i, int *j)
    {
      int coolInt;
    
      if (i > j) {
        coolInt = *i;
        *i = *j;
        *j = coolInt;
      }
    
      return;
    }


    Any ideas? Thanks!
    Last edited by Salem; 03-19-2020 at 11:33 PM. Reason: Removed crayola

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Your test should be
    if (*i > *j)

    You want to compare what the pointers point to, not the pointers themselves.

    > create a static function called ascending2()
    You forgot to make it static, not that that had any bearing on the functionality.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Mar 2020
    Posts
    3
    Ohhh of course. Thank you! And yeah I haven't made it static yet.

    Thanks again for the help!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Project involving C
    By DeanWinchester in forum Networking/Device Communication
    Replies: 0
    Last Post: 12-26-2012, 11:47 AM
  2. Replies: 23
    Last Post: 05-11-2008, 07:12 AM
  3. Need a little help with my Hw, involving reading from files
    By green11420 in forum C++ Programming
    Replies: 8
    Last Post: 03-27-2008, 10:16 AM
  4. Very stupid question involving pointers
    By 7smurfs in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 06:15 PM
  5. Replies: 2
    Last Post: 03-13-2003, 09:40 AM

Tags for this Thread