Thread: pointer problem

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    16

    pointer problem

    hi!
    I have problem whit pointer.
    The program prints out: 1-2-3-4....9

    Code:
    #include <stdio.h>
    void inc_count(int *count_ptr)
    {
        int h=(*count_ptr)++;
    	printf(" %d",h);
    }
     
    int main()
    {
        int  count = 0;     /* number of times through */
     
        while (count < 10)
            inc_count(&count);
     
        return (0);
    }
    if I write without pointer, I can not stop the while loop. why?
    Code:
    #include <stdio.h>
    void inc_count(int  count_ptr)
    {
        int h=(count_ptr)++;
    	printf(" %d",h);
    }
     
    int main()
    {
        int  count = 0;     /* number of times through */
     
        while (count < 10)
            inc_count(count);
     
        return (0);
    }

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Without a pointer, the value of 'count' never changes. C is a 'pass by value' language. All it does is take the value stored inside 'count', and pass that to the function. It doesn't actually pass the variable, so the variable itself doesn't get changed.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,533
    Well, when you don't use a pointer in your function, you are using a local copy of the variable. When the function executes, it operates only on the local copy that it has been given, and does not affect the original value at the caller. When you use a pointer, you have the option of manipulating the original directly, depending on how you want to do things. In your case here, your 'count' variable in main is not being incremented in the second program at all, hence the reason why the while loop does not end.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointer to pointer realloc problem
    By prakash0104 in forum C Programming
    Replies: 14
    Last Post: 04-06-2009, 08:53 PM
  2. Another pointer problem
    By mikahell in forum C++ Programming
    Replies: 21
    Last Post: 07-20-2006, 07:37 PM
  3. Pointer problem
    By mikahell in forum C++ Programming
    Replies: 5
    Last Post: 07-20-2006, 10:21 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. pointer problem
    By DMaxJ in forum C Programming
    Replies: 4
    Last Post: 06-11-2003, 12:14 PM