How to create a variable-length string with the character X in C

I am new to C and am having string issues. How to create a variable-length string containing the specified character in C? This is what I tried, but getting a compiler error:

int  cLen     = 8    /* Specified Length    */ 
char chr      = 'a'; /* Specified Character */
char outStr[cLen];
int  tmp      = 0;
while (tmp < cLen-1)
  outStr[tmp++] = chr;

outStr[cLen-1] = '\0';

/* outStr = "aaaaaaaa" */
+5
source share
4 answers

You can try:

char *str = malloc(cLen + 1);
memset(str, 'a', cLen);
str[cLen] = 0;
+6
source

Strings in C may not be as flexible as you want at a glance.

What you did with "char outStr []" was to indicate that you need a char pointer that can be repeated using the array syntax ... it does not create a real store for characters, because you never mentioned how much you would like to save.

C , . , : , , , ; , .

, ,

#include <stdlib.h>

char *cpString;

"n"

cpString=malloc(n*sizeof(char));

strcat, printf, , n-1 charaters ( ). ,

memset(cpString,X,n-1);
cpString[n]=0;

XXXX... XXX\0, n-1 .

cpString, , ,

if (cpString !=0)
{
 free(cpString);
 cpString=0;
}
cpString=malloc(n*sizeof(char));

( "" ) ​​ n.

, free(), malloc() free().

+4

strncat(), - , :

void repeated_string(char *out, size_t len, char v)
{
  for(; len > 0; --len)
    *out++ = v;
  *out = '\0';
}
+2

:

1) () , . :

int cLen = 8; /* Specified Length */

, 8. NULL-, 7 . , , , :

int cLen = 9; /* Specified Length (8) + 1 for NULL */

2) char :

char chr = "a";

. :

char chr = 'a';

After that, your code should work.

+1
source

All Articles