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

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

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top