Question

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);
}
Was it helpful?

Solution

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:

#include <stdio.h>

#define RAND_LENGTH 100

char *randstring (char *buffer, int length);

int main (int a, char **b){
    char buffer[RAND_LENGTH + 1];
    printf("%s", randstring(buffer, RAND_LENGTH));
}

char *randstring (char *buffer, int length){
    int i = length;
    while(--i >= 0) {
        buffer[i] = (rand() % 2) ? '1' : '0';
    }
    buffer[length] = 0;
    return buffer;
}

OTHER TIPS

Try this:

int i = 100;

while(i-- >= 0) buffer[i] = rand() % 2;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top