What I’m trying to accomplish is generating 100 random 0’s and 1’s add them all into one variable and then print it. What I have right now I don’t know how to make work. If someone could explain what I’m doing wrong, I would be very grateful.
randstring (void){
int i;
int num;
char buffer[101];
i=100;
while(i>0, i--){
num = rand()%2;
strcpy(buffer, num);
}
return(buffer);
}
What i have now is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main (void){
printf("%f", randstring());
}
randstring (void){
int num;
char buffer[101];
int i = 100;
while(i-- >= 0) buffer[i] = rand() % 2;
return(buffer);
}
How about
buffer[i] = (rand() % 2) ? '1' : '0';in the loop body?And I’d do buffer[100] = 0;
But the worse problem is that you can’t return buffer, because as soon your function exits, it would be overwritten. It is allocated on the stack, and the stack gets reused when function exits. You need to either do malloc and free, or pass buffer and its length to this function.
Which gives us: