Why is 0 a very common integer for the last values ​​of my dynamically created array?

I am currently writing a simple function to calculate the sum of two vectors. Being new to C, I decided that I created some β€œpsuedo-random” values ​​for my vectors and also randomized their length, which is more than necessary for this exercise.

Basically, I just started writing my code and wanted to see what the values ​​of my array are.

Here is the code:

#include <stdio.h> #include <stdlib.h> #include <time.h> int vectorSum(int x[], int y[], int n, int sum[]) { } void display_Array(int *a, int len){ //Declerations int i; for(i=0; i<len; i++) { printf("%d ", a[i]); } printf("\n"); } //Implement a nice randomizing function...Fisher-Yates shuffle int main(void){ //Generate a random length for the array srand(time(NULL)); int N = (rand()*rand())%100; //Declarations int *x = (int *) malloc(N * sizeof(*x)); //Because I don't know how large my array is ahead of time int *y = (int *) malloc(N * sizeof(*y)); int i; //Fill the arrays for(i=0; i<10; ++i) { x[i] = (rand()*rand())%100000; y[i] = (rand()*rand())%100000; } display_Array(x, N); getchar(); //Main execution... } 

Please note that this code is not next to the finished one - feel free to criticize as much as you like. I know that this is far from polished. However, I noticed something strange. My result often follows this pattern:

 w, x, y...z, 0, 0, 0, 0, 0, 0, 0, 0. 

Most often, the last values ​​in my array will be 0. Not always, but more often than not. In addition, this pattern is usually found in multiples. For example, the last two values ​​are 0, 0, then I run the program again, the last four digits: 0, 0, 0, 0, etc.

So why is this happening? I have suspicions, but I would like to hear other thoughts.

+4
source share
2 answers

Change this line of code:

  for(i=0; i<10; ++i) 

to

 for(i=0; i<N; ++i) 

Also, do not use rand() * rand() , it will create an integer overflow. Instead, use only rand() .

+4
source

C does not initialize array values. Thus, what you found in the cells that were not installed is just the contents of the non-erased memory (and when you iterate over all the selected cells and set the values ​​only from the first 10, there are many of them). If your memory was "clean", then you will most likely see zeros, but if there is some garbage from previous iterations / other programs, you can get any values.

+4
source

Source: https://habr.com/ru/post/1502956/


All Articles