我的程序运行正常,但最后仍然显示 Segmentation fault
My program is working properly but still at the end its showing Segmentation fault
- gdb 已经尝试过:0
void Reverse(struct Array *arr)
{
int i, j;
for (i = 0, j = arr->length - 1; i < j; i++, j--)
{
swap(&arr->arr[i], &arr->arr[j]);
}
}
void Reverse2(struct Array *obj)
{
int *b;
int i, j;
b = new int;
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
b[j] = obj->arr[i];
for (i = 0; i < obj->length; i++)
obj->arr[i] = b[i];
}
void Display(struct Array obj1)
{
int i;
cout << "yOur elements are: ";
for (i = 0; i < obj1.length; i++)
cout << obj1.arr[i] << " ";
}
int main()
{
struct Array obj = {{9, 8, 7, 6, 5, 3}, 10, 6};
cout << "your array is: ";
Display(obj);
cout << "\nAfter reversing using swap ";
Reverse(&obj);
Display(obj);
cout << "\nAfter reversing: ";
Reverse2(obj);
Display(obj);
return 0;
}
这是输出
- 你的数组是:y我们的元素是:9 8 7 6 5 3
- 使用swap反转后y我们的元素是:3 5 6 7 8 9
- 逆向后:y我们的元素是:3 5 6 7 8 9 段错误
您的代码分配了一个整数,但随后将该整数视为一个数组。这里
b = new int;
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
b[j] = obj->arr[i];
应该是
b = new int[obj->length];
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
b[j] = obj->arr[i];
- gdb 已经尝试过:0
void Reverse(struct Array *arr)
{
int i, j;
for (i = 0, j = arr->length - 1; i < j; i++, j--)
{
swap(&arr->arr[i], &arr->arr[j]);
}
}
void Reverse2(struct Array *obj)
{
int *b;
int i, j;
b = new int;
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
b[j] = obj->arr[i];
for (i = 0; i < obj->length; i++)
obj->arr[i] = b[i];
}
void Display(struct Array obj1)
{
int i;
cout << "yOur elements are: ";
for (i = 0; i < obj1.length; i++)
cout << obj1.arr[i] << " ";
}
int main()
{
struct Array obj = {{9, 8, 7, 6, 5, 3}, 10, 6};
cout << "your array is: ";
Display(obj);
cout << "\nAfter reversing using swap ";
Reverse(&obj);
Display(obj);
cout << "\nAfter reversing: ";
Reverse2(obj);
Display(obj);
return 0;
}
这是输出
- 你的数组是:y我们的元素是:9 8 7 6 5 3
- 使用swap反转后y我们的元素是:3 5 6 7 8 9
- 逆向后:y我们的元素是:3 5 6 7 8 9 段错误
您的代码分配了一个整数,但随后将该整数视为一个数组。这里
b = new int;
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
b[j] = obj->arr[i];
应该是
b = new int[obj->length];
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
b[j] = obj->arr[i];