Home > Software engineering >  Why Does the function doesn't take the value
Why Does the function doesn't take the value

Time:07-23

I am working on a problem in C that takes the starting and ending time as input and suggests all possible one hr. slots, I have written a simple function in my code, and when I run it, I get no errors, but I am getting irrelevant output, when I ran my code through gdb then I saw my function is not accepting the input data instead taking it as 0

#include<stdio.h>
#include<stdlib.h>

int solve(int* L, int* R, int* N)
{
    int slot[2];
    int i, j;
    if (L[0] == 1)
    {
        slot[0] = L[0];
        slot[1] = L[0]   1;
    }

    for (i = 1; L[i] != 0; i  )
    {
        for (j = 0; R[j] != 0; j  )
        {
            if (R[j] < L[i   1])
            {
                slot[0] = R[j];
                slot[1] = R[j]   1;
            }
        }
    }
    for (i = 0; i < *N; i  )
    {
        printf("%d\t", slot[i]);
    }
    return 0;
}


int main()
{
    int N = 0;
    int* L, * R;
    int i;
    scanf("%d", &N);
    printf("%d", N);
    L = (int*)calloc(N, sizeof(int));
    R = (int*)calloc(N, sizeof(int));

    for (i = 0; i < N; i  )
    {
        scanf("%d\t", &L[i]);
    }
    for (i = 0; i < N; i  )
    {
        scanf("%d\t", &R[i]);
    }

    for (i = 0; i < N; i  )
    {
        printf("%d\t", L[i]);
    }
    for (i = 0; i < N; i  )
    {
        printf("%d\t", R[i]);
    }
    solve(L, R, &N);
    free(L);
    free(R);

    return 0;
}

please help me in finding error in my code

CodePudding user response:

L[i] != 0 style condition in your loops is likely going over the bounds your array. Since you read N numbers, you likely either meant to loop to N (possibly 1 less since you use [i 1]) or you meant to L = (int*)calloc(N 1, sizeof(int)); to ensure 0 terminator. Naturally same goes for R, except you never use [j 1].

CodePudding user response:

When I debug your code, I see that the input data is accepted. The problem I saw was, when it comes to the for loops inside this solve function, L[i] != 0 or R[j] != 0 makes the loop like an infinite loop or so because the code gives irrelevant nonsense numbers to the more elements than you specified (number N) for L and R arrays. When I wrote for(i=0; i<*N; i ) and for(j=0; j<*N; j ) it can end the loop with the elements that you specified.

  • Related