J.ba
J.ba

Reputation: 35

Swap Using Pointer Array

I am a beginner of C programming. The code of interchange v[i] and v[j] from the book is :

void swap2(char *v[], int i, int j) {
    char *temp;

    temp = v[i];
    v[i] = v[j];
    v[j] = temp;
}

I am not sure whether I got this correct. I think v here is an array which stores pointers, so v[i] and v[j] are pointers. Here temp is also a char pointer, but it makes me feel that temp = v[i]; this statement says a pointer v[i] is assigned to an address, and I think if we change char *temp into char temp will make the function correct. Could someone help me with this?

Upvotes: 2

Views: 617

Answers (2)

user3078414
user3078414

Reputation: 1937

this statement says a pointer v[i] is assigned to an address

You seem to be confusing an array of characters with an array of character pointers: v[i] is simply the i-th member of an array consisting of char *.

In C everything is passed by value, so are the pointers. You are right in assuming that v[] is an array storing char pointers.

The code is valid because the pointers are being swapped, not the char variables pointed at: v[i] and v[j] are pointers, therefore temp should be a pointer as well.

The following test code demonstrates it from the caller's point of view: you can easily observe what is happening in your function. Pointers are being passed as values which are getting swapped, but the char variables that they point at are left as they are (b and c in this example).

#include <stdio.h>

void swap2(char *v[], int i, int j) {
    char *temp;

    temp = v[i];
    v[i] = v[j];
    v[j] = temp;
}

int main (void)
{
    char a = '1', b = '2', c = '3', d = '4', e = '5';
    char *v[5] = {&a, &b, &c, &d, &e};

    for(int i = 0; i < 5; i++)
        printf("%p:%c ", (void*)(v[i]), *(v[i]));
    printf ("\n");

    swap2(v, 1, 2);

    for(int i = 0; i < 5; i++)
        printf("%p:%c ", (void*)(v[i]), *(v[i]));
    printf ("\n");
    printf("b = %c\n", b);
    printf("c = %c\n", c);
return 0;
}

Upvotes: 1

dbush
dbush

Reputation: 223699

The function is correct as is.

v is declared as an array of char *. So each v[i] is a char *. Therefore, you use a char * when performing the swap.

Upvotes: 3

Related Questions