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