How to generate a string in C?

For example in Python, I would do this:

a = '' for i in range(10): a += '#' print(a) 
  • 2
    string is an array of bytes. so for(i=0;i<10;i++) a[i]='#'; a [10] = 0; ` - Mike
  • one
    A string in C is an array of characters with a null character at the end. So first you need to decide how you are going to create the array itself (something you don’t have to worry about in Python). That is what will be the essence of the question in C. And already filling it with # characters or something else is not a problem. - AnT
  • one
    In the python, you can write a = 10 * "#" - Vladimir Martyanov

1 answer 1

Your code is translated:

 char a[11] = {0}; for(int i = 0; i < 10; ++i) a[i] = '#'; puts(a); 

Like that.
There are other options ...

If dynamically ...

 int n = 20; char * a = (char)malloc(sizeof(char)*(n+1)); for(int i = 0; i < n; ++i) a[i] = '#'; a[n] = 0; puts(a); // и, по окончании работы, когда строка более не нужна free(a); 
  • and how in the line for(int i = 0; i < 10; ++i) change 10 to the entered number? (or variable) - lalalala
  • @lalalala: well, just take a variable and write instead of the number 10 (well, then dynamically allocate the memory for the line) - Mike
  • @lalalala See Augmented Answer - Harry
  • @Harry, + memset(a, '#', 10); :-) - PinkTux
  • The asterisk is lost - char * a = (char *)malloc(... (However, the C type can be omitted, since void * , which returns malloc is automatically cast to any pointer) - avp