0

This is C programming code that I have written. When I run this code it shows debug error the visual code is showing this warning as well.

Warning 6385 Reading invalid data from 'my_newarray': the readable size is '4' bytes, but '8' bytes may be read.

My code is:

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

int main(void)
{
    int n;   
    printf("enter the size of an array: ");

    scanf_s("%i", &n);

    int my_array[] = { calloc((n + 1), sizeof(int)) };  
    int my_newarray[] = { calloc((n + 1), sizeof(int)) };

    printf("enter only 0s and 1s n times:\n");
    for (int i = 0; i < n; i++)
    {
        scanf_s("%i", &my_array);
    }

    for (int j = 0; j < n; j++)
    {
        if (my_array[j] > my_array[j + 1])
        {
            my_array[j] = my_newarray[j + 1];
        }
    }
    for (int k = 0; k < (n+1); k++)
    {
        printf("%i\n", my_newarray[k]);
    }

    free(my_array);
    free(my_newarray);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Ouch! Syntax, syntax, syntax... `int *my_array = calloc((n + 1), sizeof(int));`, you cannot assign an address to an *Array*, you must use a *Pointer*, there are no `{...}` (brace initializer syntax) needed. (same for `my_newarray`) – David C. Rankin Feb 13 '21 at 09:25
  • Also always ***Validate*** every input, e.g. `if (scanf_s("%i", &n) != 1) { /* handle error */ return 1; }` – David C. Rankin Feb 13 '21 at 09:31
  • You need a C book https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list – 0___________ Feb 13 '21 at 10:37

1 Answers1

2

These declarations

int my_array[] = { calloc((n + 1), sizeof(int)) };  
int my_newarray[] = { calloc((n + 1), sizeof(int)) };

are incorrect. In fact you are trying to create arrays with the element type int that have single elements that are initialized by a value of the type void * that is returned by calls of calloc.

You need to declare pointers like

int *my_array = calloc((n + 1), sizeof(int));  
int *my_newarray = calloc((n + 1), sizeof(int));

Also this call

scanf_s("%i", &my_array);

is incorrect. It seems you mean either

scanf_s("%i", &my_array[i]);

or

scanf_s("%i", my_array + i);

That is you need to fill elements of the allocated array except the last element that was already zero initialized by using a call of calloc.

Also this assignment

my_array[j] = my_newarray[j + 1];

and the following loop

for (int k = 0; k < (n+1); k++)
{
    printf("%i\n", my_newarray[k]);
}

do not make a great sense because all elements of the array my_newarray were zero-initialized by a call of calloc. So you could just write

my_array[j] = 0;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335