开发者

Need help on understanding pointers in c

I'm having trouble understanding pointers concept and below is the code. Why the swap(&a1, &a2) out puts the -5, 6 rather than 6, -5 ? The values are already swap right?

void swap(int *ptr1, int *ptr2){

     int temp;

      temp = *ptr1;
      *ptr1 = *ptr2;
      *ptr2 = temp;

}

int main (int argc, char *argv[]){

    void swap(int *ptr1, int *ptr2);
    int a1 = -5;
    int a2 = 6;
    int *p1 = &a1;
    int *p2 = &a2;

    NSLog(@" a1 = %i, a2 =%i", a1, a2); // out puts: -5, 6

    swap(p1,p2);
    NSLo开发者_开发百科g(@" a1 = %i, a2 =%i", a1, a2); // out puts: 6, -5

    swap(&a1, &a2);
    NSLog(@" a1 = %i, a2 =%i", a1, a2); // out puts: -5, 6
}


Your first call to swap() swapped the two values, and the second call swapped them back.


You are swapping the same thing every time(sorta) so first you swap them, and then you swap them back. a1 stored the value -5 at address1 (an address is a location in memory) a2 stores the value 6 at addess2 p1 points to addres1 p2 points to address2 swapping p1 and p2 Here you take the value of the item stored at address1 and switch it with the value of the item at address2. so now address1 holds the value 6 and address2 holds the value -5 Here p1 and p2 still point at the same addresses and a1 and a2 still return values from the same addresses but the values have been swapped. swapping &a1 and &a2 Swapping &a1 and &a2 does the same thing, the & returns the addresses as pointers, which you them pass to the swap function. Swap takes to pointers and swaps the values of the addresses they point to.

Basically, pointers point to a memory location. Your swap function takes to memory locations and exchanges the data stored in them, it does not change what memory address they are pointing to. So in both cases you are sending the same addresses, so you swap the same to location twice.


A very simple example just to get a feeling about pointers...

int i = 2; // i == 2
int *p = &i; // p == 0x00AB (say memory addres of i is 171)
int *q = p;  // q == 0x00AB q and p have the same value

p == q is true

*p == 2 is true

*p == *q is true

p = NULL;      // initializes the pointer, which is a good practice
if (*p == 2) { // don't do this as it can cause error or unpredictable results

i == 2 is still true irrespective of what you did with your pointer variable

Pointer variables could be seen or thought of as holding "special" integer values, they store a memory address, which usually is 32-bit number (unless you are running on a 64-bit address computer).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜