0

I have made a dynamic array of integers in C, here is my code

#include <stdio.h>

int main(){
   int count=0, i, input;
   int *myarr;
   myarr=(int*)malloc(4*sizeof(int));

   while(1){
     scanf("%d", &input);
     myarr[count]=input;
     count++;
     if (input == -1) break;
   }

   for (i=0; i<count; i++){
     printf("%d ", myarr[i]);
   }

   return 0;
}

From the code, I thought i clearly made an array of 4 integers only i.e myarr[0] up to myarr[3], how come when i insert even 10 integers, it still prints all of them, it doesn't print garbage as i thought it would after the fourth integer... Maybe i didn't understand the point of dynamic creating an array?? Make me straight please!

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
user3564573
  • 680
  • 1
  • 12
  • 24

1 Answers1

0

You should only access myarr[0] up to and including myarr[3].

Accessing any other index is undefined behaviour: it might work, it might not.

Also, myarr[count]==input looks like a typo. Did you mean myarr[count] = input? The way you have it is testing if myarr[count] equals input. Technically the way you have it is undefined behaviour for any element of myarr since you are making use of uninitialised data.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483