When I used calloc to dynamically allocate a 1d array, am I supposed to get the same value or different value?

StackOverflow https://stackoverflow.com/questions/22773226

Question

I saw my friend's program. When he used calloc and fill in 1d array with random gen. and compile their program, he is getting the same value of the array.

Here is my code:

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


srand(time(NULL));
int *n, s=10;

 one=(int*) calloc(s,sizeof(int));       
 for(m=0;m<s;m++)
 {
    o[m] =(rand()%20);               
    printf("%d\n",o[m]);
 }
free(one);

The outputs:

First run: First run

Second run: Second run

Was it helpful?

Solution

You are assigning to o[m] but printing out one[m].

You also need to call srand at the start of your program to initialize the random sequence.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top