(int *) variable

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bilbo

    #1

    (int *) variable

    Hello everybody.

    What does an (int *) type of variable mean?

    Thanks

    Derek

  • Sam Jervis

    #2
    Re: (int *) variable

    Bilbo wrote:[color=blue]
    > Hello everybody.
    >
    > What does an (int *) type of variable mean?
    >
    > Thanks
    >
    > Derek
    >[/color]

    It is a pointer to an int i.e. the variable stores the memory location
    of an int rather than the actual int itself.

    You use (int *) like this:

    int a;
    int *p;

    a = 42;
    p = &a; /* p now contains the memory location of a */
    *p = 21; /* a now contains the value 21 */

    So you use & to get the address of a variable, and you use * in the
    context *p to dereference the pointer i.e. to get at the value it is
    pointing to.

    Hope this helps,
    Sam

    Comment

    • Malcolm

      #3
      Re: (int *) variable


      "Sam Jervis" <sam@heffalump. me.uk> wrote in message[color=blue]
      >
      > You use (int *) like this:
      >
      > int a;
      > int *p;
      >
      > a = 42;
      > p = &a; /* p now contains the memory location of a */
      > *p = 21; /* a now contains the value 21 */
      >[/color]
      This is correct but maybe leaves the OP wondering "what is the point of
      that?".

      One answer is that a C function can return only one value. If we want a
      function "getcursorp os" we need to return both x and y.

      we do it like this.

      /* globals maintained by the cursor handling routines */
      int g_cursorxpos;
      int g_cursorypos;

      void getcursorpos(in t *x, int *y)
      {
      *x = g_cursorxpos;
      *y = g_cursorypos;
      }

      void callingfunction (void)
      {
      int cx;
      int cy;

      getcursorpos(&c x, &cy);
      printf("The cursor is at position %d %d\n", cx, cy);
      }


      The most common use however is to pass an array of integers to another
      function. For instance if we want to calculate the mean of a list of numbers
      we would write

      int mean(int *array, int N)

      However the details of pointer and arrays are maybe best left until you've
      got the idea of storing addresses in pointers.


      Comment

      Working...