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