c - seeing random numbers in my loop after the array length has been reached? -


i creating simple array in c , outputting result console see content of array is.

i using code below , whole program test.

it asks size array want, put in 6 example, , put in 6 numbers.

now when declare array @ start set maximum numbers can 10, thought meant can add 10 numbers in array.

but when put in 6 numbers , loop see in array this:

5

1

2

4

3

6

4203737

0

4225576

0


process exited after 7.421 seconds return value 0 press key continue . . .

the numbers asking 420 , 0 etc. why there

they make total index 10, want 6 or whatever number set index length?

int main(int argc, char *argv[]) {  int array[10]; int position, c, n, value;  printf("enter number of elements in array\n"); scanf("%d", &n);  printf("enter %d elements\n", n);  (c = 0; c < n; c++)   scanf("%d", &array[c]);  //printing array know in  int = 0; int sizeofarray = sizeof(array) / sizeof(array[0]); //determine length of array for(i; < sizeofarray; i++) {      printf("%d\n", array[i]);  }   return 0; } 

thank you on one, easy 1 - seems ;-)

since declared array length 10, array of length 10 (sizeof return 10*sizeof(array[0])), no matter many data points have manually set. when initialize array that's not static or global, there's no guarantee data if don't explicitly set data yourself. it's undefined behavior.

in case, data happens 0s , 4203737s because of compiler's implementation of language.

in order print elements have set, following:

int main(int argc, char *argv[]) {      int array[10];     int position, c, n, value;      printf("enter number of elements in array\n");     scanf("%d", &n);      printf("enter %d elements\n", n);      (c = 0; c < n; c++)       scanf("%d", &array[c]);      int = 0;     for(i; < n; i++) {          printf("%d\n", array[i]);      }       return 0; } 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -