【问题标题】:checking elements in an array in s (through pointers) in Cchecking elements in an array in s (through pointers) in C
【发布时间】:2022-12-02 05:30:36
【问题描述】:

I am studying the pointers and this question became interesting. I want it to be like this: we have two arrays of integers. Determine the value and number of the largest element of the first array that is not part of the second but I don't know how to make the second part of the code that will check if the largest number is not included in the second array

#include <stdio.h>

int main()
{
    long array[100], * maximum, size, c, location = 1;

    printf("Enter the number of elements in array\n");
    scanf_s("%ld", &size);

    printf("Enter %ld integers\n", size);

    for (c = 0; c < size; c++)
        scanf_s("%ld", &array[c]);

    maximum = array;
    *maximum = *array;

    for (c = 1; c < size; c++)
    {
        if (*(array + c) > *maximum)
        {
            *maximum = *(array + c);
            location = c + 1;
        }
    }

    printf("Maximum element is present at location number %ld and it's value is %ld.\n", location, *maximum);
    return 0;
}

【问题讨论】:

  • Where is the "second array"? maximum = array; does not make another array, and *maximum = *array; does not copy its content. I suggest using malloc and memcpy.
  • @WeatherVane I don't think he has the second array done yet. But yes, maximum = array does nothing here.

标签: arrays c pointers


【解决方案1】:

I think you are doing this in the wrong order. If you find the maximum first and that is in the second array, you need to find the maximum again. You should first check each number in the first array against the second. If it is in the second, change the value to LONG_MIN. Then the maximumwillbe the right answer. Basically something like this:

#include <limits.h>

int i = 0;
for (; i < n; ++i) {
    int j = 0;
    for (; j < n; ++j) {
        /* in both arrays? */
        if (arr2[i] == arr1[j]) {
            arr1[j] = LONG_MIN;
            break;
        }
    }
}

At this point any numbers in arr1 that are in arr2 will be set to LONG_MIN. Now just calculate max like you already did.

Edit: changed INT_MIN to LONG_MIN. I didn't notice you were doing long int arrays.

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 2022-12-02
    • 2022-05-09
    • 2022-12-02
    • 2022-12-01
    • 2022-12-27
    • 2022-12-27
    • 2021-11-03
    • 2022-12-28
    相关资源
    最近更新 更多