Thread: I don't understand this code

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    158

    I don't understand this code

    I have the following code for binary heaps:
    Code:
    #define Parent(x) ((x - 1) / 2)
    #define Left(x) ((2 * x) + 1)
    #define Right(x) ((2 * x) + 2)
    
    #define MAX 10
    
    void swapElem(int *a, int *b) {
    	int tmp;
    
    	tmp = *a;
    	*a = *b;
    	*b = tmp;
    }
    
    void insertHeap(Heap *h, int elem) {
    	if(h->size == MAX) return;
    	
    	h->elem[h->size] = elem;
    	h->size++;
    	
    	int idx = h->size - 1;
    	
    	while(idx && h->elem[Parent(idx)] > h->elem[idx]) {
    		swapElem(h->elem + Parent(idx), h->elem + idx);
    		
    		idx = Parent(idx);
    	}
    }
    But I don't understand the line:
    Code:
    swapElem(h->elem + Parent(idx), h->elem + idx);
    I mean, h->elem is an array, how come h->elem + idx (for instance), produce a number? I'm adding idx to h->elem but h->elem is not a value it's an array.

    What does it mean?

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by Nazgulled View Post
    I mean, h->elem is an array, how come h->elem + idx (for instance), produce a number?
    It doesn't. It produces a pointer. A pointer is what the swap() function expects, so all is well.

    If a is an array and i is an offset, then the expression a + i is equivalent to &a[i]. Does that make it clear?

  3. #3
    Registered User
    Join Date
    Mar 2006
    Posts
    158
    Yes, but I think I'll change my code to the expression &a[i], I'm more comfortable with it and I already know what it means. The way I currently have, confuses me a bit.

    Thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Extended ASCII Characters in an RTF Control
    By JustMax in forum C Programming
    Replies: 18
    Last Post: 04-03-2009, 08:20 PM
  2. Enforcing Machine Code Restrictions?
    By SMurf in forum Tech Board
    Replies: 21
    Last Post: 03-30-2009, 07:34 AM
  3. Obfuscated Code Contest
    By Stack Overflow in forum Contests Board
    Replies: 51
    Last Post: 01-21-2005, 04:17 PM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. Replies: 0
    Last Post: 02-21-2002, 06:05 PM