Thread: Pointer expression.

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    494

    Pointer expression.

    I have two functions. Both give the same result. I understand how the first function works but what happens on the second function?
    Code:
    /* function definition */
    int DataAdd1(int list[][5], int max1, int max2)
    {
    	int i,j;
    	int sum=0;
    
    	for(i=0; i<max1; i++)
    		for(j=0; j<max2; j++)
    			sum +=list[i][j];
    		return sum;
    }
    /* function defintion*/
    int DataAdd2(int *list, int max1, int max2)
    {
    	int i,j;
    	int sum =0;
    	
    	for(i=0; i<max1; i++)
    		for(j=0; j<max2; j++)
    			sum +=*(list +i*max2 +j);
    		return sum;
    }
    how does this
    Code:
    sum +=*(list +i*max2 +j);
    come out to equal this
    Code:
    sum +=list[i][j];
    i dont get it.
    When no one helps you out. Call google();

  2. #2
    Registered User
    Join Date
    Mar 2005
    Posts
    36
    Your question reverses the order of the two forms from the the way the code shows them , but to answer it:

    In the first one, list is the address of list, max2 is the length of an i-row (in index units which are each ints in this case), i is the number of them to skip ahead, so list + i * max2 addresses the start of the i-th row, adding j indexes further to the j-th element. Note that i and j are both zero-based so the "first" row or element is the zeroth row or element. The * in front of the parentheses "dereferences" the address to get the actual int

    List[i][j] refers to the j-th element in the i-th row more obviously, but possibly less efficiently (though compiler optimization should make them about the same now, this wasn't the case in early compilers).
    Last edited by Karthur; 03-13-2005 at 09:39 PM. Reason: incomplete

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. Replies: 0
    Last Post: 03-20-2008, 07:59 AM
  3. What is a virtual function pointer?
    By ting in forum C++ Programming
    Replies: 4
    Last Post: 03-05-2008, 02:36 AM
  4. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  5. scope of a pointer?
    By Syneris in forum C++ Programming
    Replies: 6
    Last Post: 12-29-2005, 09:40 PM