0

i have an error i can't seem to figure out for hours. First off the problem is:

use a recursive function to determine whether an array is 'very ascending', 'ascending', or 'not ascending',

  • if very ascending return 1 and send a pointer = 1,
  • if ascending return 1 and send a pointer = 0,
  • if not ascending return 0 and send a pointer = 0."

i have done it without recursion, but when i use the recursive function i get an error for trying to use "unhandled exception" (or memory that's not mine - i think).

On a side note: I am new to dynamic memory and i tried doing it with malloc on the recursive function.

non-recursive working function:


#include <stdio.h>
#define N 5

void inputArray(int *arr)
{
    int i;
    for (i = 0; i < N; i++)
    {
        scanf_s("%d", &arr[i]);
    }
}

int check_order(int *arr, int *n)
{
    int i;
    for (i = 0; i < N - 1; i++)
    {
        if (arr[i + 1] < arr[i])
        {
            *n = 0;
            return 0;
        }
        if (arr[i + 1] == arr[i])
        {
            *n = 0;
        }
    }
    return 1;
}

void main()
{
    int arr[N], n = 1;
    printf("enter 5 variables for array:\n");
    inputArray(&arr);
    printf("[very ascending: 1, 1] | [ascending: 1, 0] | [not ascending: 0, 0]\n");
    printf("(%d, %d)\n", check_order(&arr, &n), n);
    return 0;
}
//********************************************************************
#include <stdio.h>
#include <stdlib.h>

void inputArray(int *arr, int n)
{
    int i;
    printf("enter %d variables for array:\n", n);
    for (i = 0; i < n; i++)
    {
        scanf_s("%d", &arr[i]);
    }
    return;
}

recursive function:


int check_order_recursive(int *arr, int n, int *p)
{
    if (n < 2)
    {
        return 1;
    }
    if (arr[n - 1] < arr[n - 2])
    {
        *p = 0;
        return 0;
    }
    if (arr[n - 1] == arr[n - 2])
    {
        *p = 0;
    }
    check_order_recursion(*arr, n - 1, *p);
}

void main()
{
    int *arr, n, p = 1;

    printf("how many elemants in the array?:\n");
    scanf_s("%d", &n);
    arr = (int*)malloc(sizeof(int) * n);
    inputArray(arr, n);

    printf("[very ascending: 1, 1] | [ascending: 1, 0] | [not ascending: 0, 0]\n");
    printf("(%d, %d)\n", check_order_recursive(arr, n, &p), p);
    free(arr);
    return;
}

Barmar
  • 741,623
  • 53
  • 500
  • 612
Tiran
  • 103
  • 6

0 Answers0