Problem with pointer to pointer

Hello,

I want to swap a pointer wich points to another pointer which points to an array. I can do it if the pointer points to a variable but not to an array.



#include <iostream>

int swap(int **val1, int **val2){

int tmp=0;

tmp=**val1;
**val1=**val2;
**val2=tmp;

};



int main() {
int a=5;
int b=3;
//int a[5]={1,2,3,4,5 };
//int b[5]={22,34,56,78,89};

int *p1=0;
int *p2=0;


p1=&a;
p2=&b;

vertausche(&p1, &p2);


printf("%d\n",a);
printf("%d",b);



return 0;
}

When I try my swap function from above for an array only the first elements in the array swaps. Which is kind of logical because the Pointer **pp1 shows only to the first element but I don't know how I can swap the other elements.
I tried to do it in a for loop like this:




int tmp[5] ={0};


for(int i=0; i<5; i++) {
tmp[i] = *wert2[i];
*wert1[i]= *wert2[i];
*wert2[i] = tmp[i];

But my compiler said that this is totally wrong^^
Hopefully my problem is understandable.

So if anyone have the time and leisure to help me I will be very thankful :)












Try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

void vertausche(int *a, int *b, int size) {
    for (int i = 0; i < size; ++i) {
        int tmp = a[i];
        a[i] = b[i];
        b[i] = tmp;
    }
}

void print(int *a, int size) {
    for (int i = 0; i < size; ++i)
        std::cout << a[i] << ' ';
    std::cout << '\n';
}

int main() {
    int a[5] = {1,2,3,4,5};
    int b[5] = {22,34,56,78,89};
    int size = 5;

    vertausche(a, b, size);
    print(a, size);
    print(b, size);
}

Last edited on
Thanks for the answer. Is it possible to swap only the addresses from the pointers so the function header would look like void swap (int **a, int **b) so that I only swap the pointer ?
You could do something like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

void vertausche(int **a, int **b) {
    int *tmp = *a;
    *a = *b;
    *b = tmp;
}

void print(const int *a, int size) {
    for (int i = 0; i < size; ++i)
        std::cout << a[i] << ' ';
    std::cout << '\n';
}

int main() {
    int a[5] = {1,2,3,4,5};
    int b[5] = {22,34,56,78,89};
    int *pa = a, *pb = b;

    vertausche(&pa, &pb);
    print(pa, 5);
    print(pb, 5);
}

Or a little more C++-like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

void vertausche(int*& a, int*& b) {
    int *tmp = a;
    a = b;
    b = tmp;
}

void print(const int *a, int size) {
    for (int i = 0; i < size; ++i)
        std::cout << a[i] << ' ';
    std::cout << '\n';
}

int main() {
    int a[5] = {1,2,3,4,5};
    int b[5] = {22,34,56,78,89};
    int *pa = a, *pb = b;

    vertausche(pa, pb);
    print(pa, 5);
    print(pb, 5);
}

Last edited on
thanks a lot :)
Topic archived. No new replies allowed.