#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
#define len 10
int *randomArray(void);
int main()
{
srand(time(NULL));
int *rArray = (int *)malloc(sizeof(int) * len);
rArray = randomArray();
for (int i = 0; i < len; i++) {
printf("%d ", *(rArray+i));
}
puts("");
free(rArray);
}
int *randomArray(void)
{
int array[len] = { 0 };
for (int i = 0; i < len; i++) {
array[i] = rand() % len;
}
return array;
}
Task is to create an array of int
s and have a function fill that array with random numbers. The function randomArray()
works just fine, but for some reason the assignment rArray = randomArray()
doesn't work correctly, although some elements of rArray
are valid numbers not gibberish. Also, the last main line free(rArray);
crashes the program which is just mind numbing for me, it doesn't make any sense. If I remove the line the program doesn't crash but we all know you need to free()
a malloc()
-ed array.
Aucun commentaire:
Enregistrer un commentaire