Home > Software design >  Why does the pointers cant pass the right values(C)?
Why does the pointers cant pass the right values(C)?

Time:12-08

I was given this task:

Write a function that takes an array of integers "arr" and its size "n" and an integer "key" (It is known that the array has At least 2 integers).

The function checks and returns 1 if there are two integers in an array whose sum is less than "key", otherwise the function Returns 0. In addition if there are integers that satisfy this condition the function will pass their values ​​to "n" and "key", otherwise it will pass -1.

This is my solution:

int ex5(int* arr, int* n, int* key)
{
    while (*n > 0)
    {
        int i;
        for (i = 0; i < *n - 1; i  )
        {
            if (arr[*n-1]   arr[i] < *key)
            {
                
                *n = arr[i];
                *key = arr[*n-1];*
                return 1;
            }
        }
        --*n;
    }
    *n = -1;
    *key = -1;
    return 0;
}

And this is my main function:

int main()
{
    int arr[] = {1, 6, 2, 4, 3}, n = 5, key = 4;
    int res = ex5(arr, &n, &key);
    printf("%d %d %d", res, n, key);
}

However when i run my code the function returns me 1 and passes (n = 1, key = 1), and it should pass (n = 2, key = 1).

CodePudding user response:

*n = arr[i]; 
*key = arr[*n-1]; 

The second line in above codes reads arr[arr[i]-1]; This can be out of bound if for example arr[i] is 1000, and you only 5 elements in the array. There is no relation between the values in the array and the array size. At least flip the order:

*key = arr[*n-1]; 
*n = arr[i];

You can also use two loops to make the code easier. Example

int ex5(int* arr, int *size, int *key)
{
    for (int i = 0; i < *size; i  )
        for (int k = i   1; k < *size; k  )
            if (arr[i]   arr[k] < *key)
            {
                *key = arr[i];
                *size = arr[k];
                return 1;
            }
    return 0;
}

CodePudding user response:

Write 2 for loops this would meet the condition.

int ex5(int* arr, int *size, int *key)
{
int i=0;
while(i<*size)
{
int k=i 1;
while(k<*size)
{
if (arr[i]   arr[k] < *key)
{
*key = arr[i];
*size = arr[k];
return 1;
}
i  ;
}
return 0;
}
  • Related