pointerbsp



  • nabend,

    kann mir jemand sagen, wieso folgender code nicht funktioniert? die erste 6 wird noch ausgedruckt, dann schmiert das programm ab =(.

    #include <stdio.h>
    struct x{
    	int y;
    };
    
    void foo(struct x *my_x){
    	struct x a;
    	my_x=&a;
    	my_x->y=6;
    	printf("%d\n",my_x->y);
    }
    
    int main(void){
    	struct x *pa;
    	foo(pa);
    	printf("%d\n",pa->y);
    	return 0;
    }
    


  • weil du pa auf

    struct x a;
    

    zeigen lässt. da

    struct x a;
    

    aber lokal in foo() ist, existiert es nach aufruf von foo() nicht mehr. demnach wird ein versuch auf pa nach foo() zuzugreifen fehlschlagen müssen.



  • Und wieso geht das dann nicht? :

    #include <stdio.h>
    struct x{
    	int y;
    };
    
    struct x a;
    
    void foo(struct x *my_x){	
    	my_x=&a;
    	my_x->y=6;
    	printf("%d\n",my_x->y);
    }
    
    int main(void){
    	struct x *pa;
    	foo(pa);
    	printf("%d\n",pa->y);
    	return 0;
    }
    


  • du kannst nicht den wert eines funktionsparameters in der funktion ändern, in deinem falle die adresse von 'a'. ok, du kannst, allerdings hat dies keinen effekt auf die variable die du im aufrufer übergibst (also pa behält den selben wert, den es vorher hatte).

    dies würde zB gehen

    struct x{
        int y;
    };
    
    struct x a;
    
    void foo(struct x *my_x){   
    
        my_x->y=6;
        printf("%d\n",my_x->y);
    }
    
    int main(void){
        struct x *pa = NULL;
        pa=&a;
        foo(pa);
        printf("%d\n",pa->y);
        return 0;
    }
    


  • Ahhh, da wird mir einiges klar. Vielen, vielen dank 😋 👍


Anmelden zum Antworten