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
    23,787
    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.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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, 02:51 PM
  2. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  3. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 12:47 AM

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