Thread: very basic pointer questions--pls help

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Code:
    /* i is a pointer to an int, and has not been given a valid address yet */
    int *i; 
    
    /* i_len is an int, and has been assigned the value of zero */
    int i_len=0;
    
    /* i_len is an int still, and has been incremented to 1. i_len is being used as an 
       index in an array, but i has not yet been given memory space. This is an error,
       and the results are undefined. If it's kept up. It will crash the program.
    
       The place in memory that is one int past i in memory, has been assigned the 
       value of one, although the pointer i doesn't own this memory location.
    */
    i[i_len++]=1;
    
    /* Same as above, except one more int's size up from the space i is pointing to.
       This is undefined, and may cause anything to happen, from a program crash, to   
       a wrong answer, to nothing noticeable.
    
       The more it's continued, the more likely the "anything" will be more severe.
    */
    
    i[i_len++]=2;
    In the above scenerio, does it mean 'i' is being set as a pointer to 1 dimensional array, which sets 1,2 one after another sequentially into the array? The coder later pass the 'i_len' value as return from function. I understand 'i_len' is just an array index but could it mean something else?
    There is a close relationship between pointers and arrays, in C. i is a pointer, but not an array, and has been given no memory ("real estate") of it's own. It is a "squatter", if you will.

    If i were allocated (given) some memory, ( with malloc() or calloc() )it could be used as a "dynamic" array - which is *VERY* close (but never quite the same thing), as a "real array".
    Code:
    int *i;  //a pointer, which could be allocated memory, and become a "dynamic" array.
    int i[50]; //a real array
    Last edited by Adak; 02-04-2011 at 10:27 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  2. Smart pointer questions
    By Elysia in forum C++ Programming
    Replies: 3
    Last Post: 03-13-2009, 01:54 PM
  3. Two basic questions about reflection
    By George2 in forum C# Programming
    Replies: 0
    Last Post: 06-01-2008, 08:52 PM
  4. basic questions about enum
    By George2 in forum C# Programming
    Replies: 3
    Last Post: 05-15-2008, 05:58 AM