-2

I'm trying to learn pointers in C, and here is some code I wrote to test it:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int m = 4;
    int *n;
    n = &m;

    printf("%d\n",*n);

    for (*n = 0; *n < 100; *n++){
        printf("%d\n",*n);
    }
}

As expected, that first part printed 4. But the loop did not go further than 4, and did not go to 100 as I tried to make it.

user311302
  • 97
  • 5
  • 2
    You have a problem with **operator preceedence** (look it up!). Your code invokes undefined behaviour. Use a debugger to see what's actually going on in your code (step by line). – too honest for this site Sep 17 '16 at 23:46
  • I'm very new to C; I don't know what you mean. I do see stuff about right-to-left tho online, but its not clear. However, I moved the ++ where the *n was, and it ran. But I need to be able to replicate this – user311302 Sep 17 '16 at 23:49
  • 1
    Possible duplicate of [C - cannot increment the value of a dereferenced pointer](http://stackoverflow.com/questions/14367305/c-cannot-increment-the-value-of-a-dereferenced-pointer) – Raymond Chen Sep 17 '16 at 23:49
  • 1
    `*n++` --> `(*n)++` or `++*n` – BLUEPIXY Sep 17 '16 at 23:53
  • ++*n was what I changed it to, and it incremented – user311302 Sep 18 '16 at 00:02
  • And as a newbie you could not enter the search phrase into google, of course. Sorry, but that is not even a lame excuse! What you are asking is well explained in every C book. Get one (just make sure it covers **at least** modern C, i.e. C99, better C11). – too honest for this site Sep 18 '16 at 00:10
  • 1
    `++*n` means something very different. It does not matter much here, but it is **vital** you understand the issue. And I gave you something to research. Any programmer has to think for himself. That one is a good start! – too honest for this site Sep 18 '16 at 00:20
  • Possible duplicate of [Post-increment on a dereferenced pointer?](https://stackoverflow.com/questions/859770/post-increment-on-a-dereferenced-pointer) – Bernhard Barker May 25 '17 at 12:07

1 Answers1

0

Along with the pointer notation fix suggested by others, I would write this example so that it prints m in the loop, instead of *n, so you can see that manipulating *n does have indeed an effect on the variable to which it points:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int *n, m = 4;

    n = &m;

    printf("%d\n", *n);

    for (*n = 0; *n < 100; (*n)++)
    {
        printf("%d\n", m);
    }
}
cdlane
  • 40,441
  • 5
  • 32
  • 81