Pointer dereference

This is a discussion on Pointer dereference within the C Programming forums, part of the General Programming Boards category; Hi i got the following code am trying to understand: Code: #include <stdio.h> #include <stdlib.h> int main(void) { int *x; ...

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    270

    Pointer dereference

    Hi i got the following code am trying to understand:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
       int *x;
       int i;
    
       x = (int *) malloc ( sizeof(int) * 100);
    
       for(i = 0; i < 100; i++)
          x[i] = i;
    
       for(i = 0; i < 100; i++)
          printf("%d ",x[i]);
       printf("\n");
    
       free (x);
    
       for(i = 0; i < 100; i++)
          printf("%d ",x[i]);
       printf("\n");
    }
    Its the bit in red above. I thought you have to dereference to get the value so shouldnt it be:
    printf("%d ",*x[i]);?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,624
    x[i] is equivalent to *(x + i)

    Incidentally, you should not be accessing what x points to after free(x), and there is no need to cast the return value of malloc().
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Quick Pointer Question
    By gwarf420 in forum C Programming
    Replies: 15
    Last Post: 06-01-2008, 03:47 PM
  2. Replies: 1
    Last Post: 03-24-2008, 10:16 AM
  3. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  4. How did you master pointers?
    By Afrinux in forum C Programming
    Replies: 15
    Last Post: 01-17-2006, 07:23 PM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 08:32 AM

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