Home > Software engineering >  How to change values of pointers?
How to change values of pointers?

Time:01-24

I have a problem. I have to change values of two pointers. For example pointer1 points on number a=5, pointer2 points on nmber b=10, after calling of function they need to be swapped. Pointer1 has to show on b, and pointer2 has to show on a.

void zamijeni_pokazivace(int **pok1, int **pok2) {
    int tmp;
    tmp = **pok1;
    **pok1 = **pok2;
    **pok2 = tmp;
}

int main() {
    int a = 5;
    int b = 10;
    int *pok1 = &a;
    int *pok2 = &b;
    zamijeni_pokazivace(&pok1, &pok2);
    printf("Pokazivac 1 pokazuje na %d , a pokazivac 2 na %d.", *pok1, *pok2);
}

This code passes the test. But this one not:

#include <stdio.h>

void zamijeni_pokazivace(int **pok1, int **pok2) {
    int tmp;
    tmp = **pok1;
    **pok1 = **pok2;
    **pok2 = tmp;
}

int main() {
    int a = 5;
    int b = 10;
    int *pok1 = &a;
    int *pok2 = &b;
    zamijeni_pokazivace(&pok1, &pok2);

    if (pok1 == &b) 
        printf("pok1 pokazuje na b\n"); 
    else 
        printf("pok1 NE pokazuje na b\n");

    if (pok2 == &a) 
        printf("pok2 pokazuje na a"); 
    else 
        printf("pok2 NE pokazuje na a");
}

I think number in main swap the value becasue in debugger in first if statemen it show this (10==5) instead showing (5=5) i think :)

CodePudding user response:

You're not swapping the pointers. Fixed:

void zamijeni_pokazivace(int **pok1, int **pok2) {
    int *tmp;
    tmp = *pok1;
    *pok1 = *pok2;
    *pok2 = tmp;
}
  •  Tags:  
  • Related