I am currently in the process of writing a simple function to compute the sum of two vectors. Being that I am new to C, I figured I would generate some "psuedo-random" values for my vectors and to also randomize their length - which is more than needed for this exercise.
Basically, I just started writing my code and wanted to see what the values of my array happen to be.
Here's 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...
}
Note that this code is no where near being finished - feel free to critique as much as you wish. I am aware it is far from polished. However, I noticed something odd. My output would often follow this pattern:
w, x, y...z, 0, 0, 0, 0, 0, 0, 0, 0.
More often than not, the last values in my array would be 0. Not always, but more often than not. Furthermore, this pattern usually occurs in multiples. For instance, the last two values are 0, 0, then I run the program again, the last four digits are 0, 0, 0, 0, and so forth.
So, why does this happen? I have my suspicions, but I would like to hear other's thoughts.
Change this line of code:
for(i=0; i<10; ++i)
to
for(i=0; i<N; ++i)
Besides, don't use rand() * rand()
, it will create integer overflow. Instead use just rand()
.
C
does not initialize the values of the array. So what you find in the cells that have not been set is simply the content of non-erased memory (and as you loop through all allocated cells, and set values only of first 10 ones, there are lots of them). If your memory was "clear", then you will most probably see zeros, but if there are some garbage from previous iterations/other programs - you can get any kind of values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With