Stack Overflow Asked by Ethan on February 4, 2021
#include <stdio.h>
#include <stdlib.h>
int main(){
int n;
for(int i= 0;i < 5; i++ ){
//type arrayName[arraysize];
int arrayName[5] = rand();
printf("array[%d] = %dn",i,arrayName[i]);
}
return 0;
}
I got an error about an invalid initializer for rand(); How do I add a random to the array and give it a range?
You're missing two things here:
int arrayName[5];
rand()
call doesn't return integer array, it just return one integer. So you would want to replace this:int arrayName[5] = rand();
with this:
arrayName[i] = rand();
Answered by Rohan Kumar on February 4, 2021
remember you can't initialize an array with random variables like that you must fill item by item
array[i] = rand();
you need to just change your place of define variables like this
#include <stdio.h>
#include <stdlib.h>
int main(){
int arrayName[5];
int n;
int i;
for(i = 0;i < 5; i++ ){
arrayName[i] = rand();
printf("array[%d] = %dn",i,arrayName[i]);
}
return 0;
}
and this is a function that fill an array with random numbers
void generateFunction(int* arr, int len) {
while (len-- > 0) {
*arr++ = rand();
}
}
or in simple way
void generateFunction(int* arr, int len) {
int i;
for (i = 0; i < len; i++) {
arr[i] = rand();
}
}
Answered by Ali Mirghasemi on February 4, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP