JoeWagner0
JoeWagner0

Reputation: 3

What would be the fastest way to create a string of n chars in C

What would be the fastest/shortest way to create a string of repeating characters.

For instance, n = 10, char = '*', resulting allocated string: **********

Upvotes: 0

Views: 194

Answers (3)

Chris Lutz
Chris Lutz

Reputation: 75429

char *allocate(int c, size_t n)
{
    if(!c) return calloc(n + 1);
    char *s = malloc(n + 1);
    memset(s, c, n);
    s[n] = '\0';
    return s;
}

Honestly, why are you trying to do it fastest? Why not just do it, and then speed it up later if you need to?

Particularly, if you're only creating this to output it, you could just

void printtimes(int c, size_t n, FILE *f)
{
    while(n--) fputc(c, f);
}

Upvotes: 1

David Yaw
David Yaw

Reputation: 27864

Use memset.

int n = 10;
char c = '*';

char* buf = malloc(n+1);
memset(buf, c, n);
buf[n] = '\0';

free(buf);

Upvotes: 11

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215397

memset(buf, '*', 10); buf[10]=0;

Replace '*' and 10 with the values you want, and if the length is not known in advance and could be large, use buf=malloc(n+1); to get your buffer.

Upvotes: 6

Related Questions