Weird Segmentation Fault after printing

前端 未结 2 417
暗喜
暗喜 2021-01-29 09:30

Wrote a simple swap program, works well; But gives a Segmentation Fault after printing everything.

#include 

void swap(int* p1,i         


        
2条回答
  •  甜味超标
    2021-01-29 10:18

    This should work:

    (temp is a normal int! Otherwise your using a uninitialized pointer which is undefined behaviour)

    #include 
    
    void swap(int* p1,int* p2){
    
        int temp;
        temp = *p1;
        *p1 = *p2;
        *p2 = temp;
    
    }
    
    int main(){ 
    
        int a = 9, b = 8;
    
        printf("%d %d \n",a,b);
        swap(&a, &b);    
        printf("%d %d \n",a,b);
    
        return 0;
    }
    

提交回复
热议问题