c++segmentation-faultswapreversing

My program is working properly but still at the end its showing Segmentation fault


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;
}

This is the output


Solution

  • Your code allocates a single integer, but then treats that integer as an array. Here

    b = new int;
    for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
        b[j] = obj->arr[i];
    

    should be

    b = new int[obj->length];
    for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
        b[j] = obj->arr[i];