2

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?

2
  • 1
    If you made temp a char instead of char *, you'd be assigning a char * to a char, and you'd probably get a compilation error... Commented Jun 24, 2016 at 19:59
  • A pointer is an address. Commented Jun 24, 2016 at 20:47

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your reply. But why we can write "temp = v[i]" instead of "*temp = v[i]". I think even if temp is known as a pointer, the * should still be shown.
No, because *temp is of type char, so it would be a type mismatch.
@IshanM That won't work because temp hasn't been initialized to point anywhere yet.
1

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.