c Language dynamic assignment array deduplication question.

Asked 1 weeks ago, Updated 1 weeks ago, 2 views

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int cnt, i, j;
    printf ("How many numbers do you want to enter? : ");
    scanf_s("%d", &cnt);

    int* arr = (int*)malloc(sizeof(int)*cnt);
    int* arr2 = (int*)malloc(sizeof(int) * cnt);
    int n = 1;

    if (arr != NULL & arr2 != NULL) {

        for (i = 0; i < cnt; i++) {
            printf("%dth integer input: ", i + 1";
            scanf_s("%d", &arr);
        }

        arr2[0] = arr[0];

        for (i = 0; i < cnt; i++) {
            for (j = 0; j < cnt; j++) {

                if (arr2[i] != arr[j]) {
                    arr2[i + 1] = arr[j];
                    n++;

                    break;
                }
            }
        }

        for (i = 0; i < n; i++) {
            printf("%d", &arr[i]);
        }

    }
    free(arr);
    free(arr2);

    return 0;

}

I want to get the array as a dynamic memory allocation, so I want to eliminate duplicate values. arr[0] = arr2[0]; line error Read access violation. What should I do?

c pointer array

2022-09-20 13:13

1 Answers

scanf_s("%d", &arr]); is invalid, causing the dynamically assigned arrr to be corrupted. scanf_s("%d", &arr[i]); should be modified.

        for (i = 0; i < cnt; i++) {
            printf("%dth integer input: ", i + 1";
            scanf_s("%d", &arr[i]);
        }

printf("%d", &arr[i]); is also invalid. I don't need a pointer. printf("%d ", arr[i]);


2022-09-20 13:13

If you have any answers or tips


© 2022 pinfo. All rights reserved.