Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,948 questions

51,890 answers

573 users

How to create a string with a repeated character N times in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* repeat_char(char ch, int n) {
    // Allocate memory for the string (+1 for null terminator)
    char* result = (char*)malloc((n + 1) * sizeof(char));
    if (result == NULL) {
        perror("Memory allocation failed");
        return NULL;
    }

    // Fill the string with the character
    memset(result, ch, n);

    // Null-terminate the string
    result[n] = '\0';

    return result;
}

int main() {
    char ch = '*';
    int n = 10;

    char* repeated_string = repeat_char(ch, n);
    if (repeated_string != NULL) {
        printf("Repeated string: %s\n", repeated_string);
        free(repeated_string); // Free allocated memory
    }

    return 0;
}

  
  
/*
run:
  
Repeated string: **********
  
*/

 



answered Jul 27, 2025 by avibootz
...