Access violation reading location 0xFFFFFFFE

-5
void inputArray(int* *pa, int *n)
{
    do {
        printf("Input the elements: ");
        scanf_s("%d", n);
        if (*n < 0)
        {
            printf("Error! Input again\n");
        }
    } while (*n < 0);
    *pa = (int*)malloc(*n * sizeof(int));
    for (int i = 0; i < *n; i++)
    {
        printf("Elements a[%d]: ", i);
        scanf_s("%d", pa + i);
    }

}

void outputArray(int* *pa, int n)
{
    printf("\nContent of the array\n");
    for (int i = 0; i < n; i++)
    {
        printf("a[%d] = %d\n", i, *(pa + i));
    }
}

int main()
{
    int *A;
    int n;
    inputArray(&A, &n);
    outputArray(&A, n);
    free(A);
    _getch();
    return 0;
}

When the program display the array, I got the error "Exception thrown at 0x00AD372D (ucrtbased.dll)" I'd tried many times to fix the error, but it still displays the error when the program displays the output of array, please give me some advice. Thanks for reading.

c
asked on Stack Overflow Mar 9, 2017 by Thomas Vu

2 Answers

1

You have a double pointer int* *pa in you function inputArray, of wich you allocated space for *pa. and you are reading value to pa. First you should allocate memory for pa then read value to it.

 for (int i = 0; i < *n; i++)
{
    pa[i] = malloc(sizeof(int));
    printf("Elements a[%d]: ", i);
    scanf_s("%d", pa[i]);
}
answered on Stack Overflow Mar 9, 2017 by Shihab Pullissery • edited Mar 9, 2017 by Shihab Pullissery
1

A debugger will have shown you where the problems are.

You pass the address of a pointer to inputArray and get it as an int **: fine

You allocate the array with *pa = (int*)malloc(*n * sizeof(int)); : almost fine. All indirections levels are correct, but you should not cast malloc in C (should be: *pa = malloc(*n * sizeof(int));)

But scanf_s("%d", pa + i); is plain wrong. pa is a pointer that contains the address of the allocated array, so the array is at *pa not at pa. You should write scanf_s("%d", *pa + i);

For outputArray, you have no reason to pass a pointer to the array. But if you do, the values will be at (*pa)[i], not at *(pa + i) which is the same as pa[i], so you should use : printf("a[%d] = %d\n", i, (*pa)[i]);.

But the correct way would be:

void outputArray(int *pa, int n)
{
    printf("\nContent of the array\n");
    for (int i = 0; i < n; i++)
    {
        printf("a[%d] = %d\n", i, pa[i]);
    }
}
...
outputArray(A, n);
answered on Stack Overflow Mar 9, 2017 by Serge Ballesta

User contributions licensed under CC BY-SA 3.0