Question!

This is a discussion on Question! within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> void dothing(int a, int b[]); int main() { int x = 7, y[] = {11}; dothing(x, y); ...

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    6

    Question!

    Code:
    #include <stdio.h>
    void dothing(int a, int b[]);
    int main()
    {
        int x = 7, y[] = {11};
        dothing(x, y);
        printf("%i %i\n", x, y[0]);
        return 0;
    }
    void dothing(int a, int b[])
    {
         a++;     
         b[0]++;
         return;
    }
    Why is the answer '7 12' and not '8 12'? Since a is being incremented..

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,304
    Quote Originally Posted by sKeL`
    Why is the answer '7 12' and not '8 12'? Since a is being incremented..
    Because a is initialised to be a copy of x, but a is not x.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2009
    Posts
    46
    Because a is initialised to be a copy of x, but a is not x.
    i.e you should pass by reference like this

    Code:
    #include <stdio.h>
    void dothing(int *a, int b[]);
    int main()
    {
        int x = 7, y[] = {11};
        dothing(&x, y);
        printf("%i %i\n", x, y[0]);
        return 0;
    }
    void dothing(int *a, int b[])
    {
         *a=*a+1; 
         b[0]++;
         return;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 03:51 PM
  2. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 06:51 PM
  3. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 01:52 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 10:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM

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