c**********e 发帖数: 2007 | 1 void swap(int *a, int *b) {
int *c;
*c=*a;
*a=*b;
*b=*c;
return;
}
int main() {
int x=5, y=10;
swap(&x, &y);
cout << x << " " << y << endl;
return 0;
}
The correct result is printed, but there is a segmentation fault. Is it
because *c is a local variable? |
c**********e 发帖数: 2007 | 2 void swap(int *a, int *b) {
int c;
c=*a;
*a=*b;
*b=c;
return;
}
This one is always correct. But isn't the other one only assigned a value of
*c? I do not understand why the other one causes data Segmentation fault.
Help please. |
c****x 发帖数: 61 | 3 *c没初始化
【在 c**********e 的大作中提到】 : void swap(int *a, int *b) { : int c; : c=*a; : *a=*b; : *b=c; : return; : } : This one is always correct. But isn't the other one only assigned a value of : *c? I do not understand why the other one causes data Segmentation fault. : Help please.
|
m******e 发帖数: 353 | 4 没给c分配内存啊
【在 c**********e 的大作中提到】 : void swap(int *a, int *b) { : int c; : c=*a; : *a=*b; : *b=c; : return; : } : This one is always correct. But isn't the other one only assigned a value of : *c? I do not understand why the other one causes data Segmentation fault. : Help please.
|
c**********e 发帖数: 2007 | 5 You are right. The following statement solves the problem.
int *c =new int;
【在 m******e 的大作中提到】 : 没给c分配内存啊
|