我在尝试交换两个变量中的值时遇到段错误。我的代码是:
void swap(int *a,int *b){
int *temp;
*temp=*a;
*a=*b;
*b=*temp;
}
int main(){
int i=1,j=0;
printf("Before %d,%d\n",i,j);
swap(&i,&j);
printf("After %d,%d\n",i,j);
return 0;
}
我收到以下错误:
Before 1,0
After 0,1
Segmentation fault (core dumped)
对我来说神秘的是在成功交换值后产生了错误。错误是什么?我需要在任何地方强制转换指针吗?
最佳答案
你的指针 int *temp;
没有指向任何东西。
因此,当您的程序执行*temp=*a;
时,它会将a
的值放入随机内存块中。
试试这个修复:
void swap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
更新:
补充问题:
Suppose I want to use temp as a pointer variable and not as a regular variable, is there any way to get my program executed or I need to leave my stubbornness?
回答:你可以试试这个:
void swap(int *a,int *b){
int *temp;
temp = malloc(sizeof(int));
if (temp == NULL)
return;
*temp=*a;
*a=*b;
*b=*temp;
free(temp);
}
关于c - C 中的段错误。尝试使用指针交换两个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26113257/