Thread: Help understanding this function...

  1. #1
    Registered User
    Join Date
    Oct 2011

    Help understanding this function...

    #include <stdio.h>
    #define size 3
        void setarr1(int b[ ]);
        void setarr2(int b);
        void main ( )
            int a[size] = {2,7,6}; //size = 3
            int i;
            for(i = 0; i < size; i++) 
                if (i % 2 ) 
            for (i = size - 1; i >= 0; i--)
                printf("%d\n", a[i]);
        void setarr1(int b[ ]) 
            int i, a = size-1; 
            for (i = 0; i < size; i++) 
                b[i] += b[i] + a--; 
        void setarr2 (int b)
            b -= size;
    Above is the function that I have try a long time to figure its output. I have try to trace out but I still don't know why its output will be 24, 31, 14. So, I really hope that someone help me understand this function pls ~ Very thanks you.

  2. #2
    Make Fortran great again Epy's Avatar
    Join Date
    Sep 2009
    California, USA
    We can't do this for you, but we can give you some hints.

    First off, look at setarr2(). The argument to this function is an int, NOT a pointer to an int. Therefore, the b -= size does nothing to the original value; it decrements the copied value. So there might as well not be a setarr2() at all.

    setarr1()'s argument is a pointer and the array 'a' is passed to it, so a will definitely be changed. Keep in mind that the 'a' in setarr1() is not the same 'a' that is passed to it. Also, remember that a-- evaluates to the original value of a, it then decrements the variable after evaluating to that original value.

    Nothing to do with the problem itself, but "void main()" isn't the preferred definition for main; use int main(void) or int main(int argc, char *argv[]).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help understanding hash function
    By in forum C Programming
    Replies: 3
    Last Post: 06-14-2011, 11:33 AM
  2. Need help with understanding a recursion function
    By CS_Student8337 in forum C Programming
    Replies: 7
    Last Post: 02-10-2009, 06:52 AM
  3. Help understanding result of Function
    By deadhippo in forum C Programming
    Replies: 7
    Last Post: 04-05-2008, 02:56 AM
  4. need help understanding this function
    By Lince in forum C Programming
    Replies: 4
    Last Post: 08-04-2007, 10:29 AM
  5. Help understanding function header
    By BrewBuster in forum C Programming
    Replies: 3
    Last Post: 02-24-2003, 11:01 PM