我在堆上声明了一大块内存。
char *str;
str = (char *)malloc(sizeof(char) * 10);
我有一个常量字符串。
const char *name = "chase";
因为 *name
比 10
短,所以我需要用 chase
加上 5 个空格来填充 str
。
我尝试循环并设置 str[i] = name[i]
但有些东西我不匹配,因为我无法为额外的字符分配空格。这就是我要去的地方,只是试图用所有空格填充 str
以开始
int i;
for (i = 0; i < 10; i++)
{
strcpy(str[i], ' ');
printf("char: %c\n", str[i]);
}
最佳答案
正如其他人指出的那样,您需要
//malloc casting is (arguably) bad
str = malloc(sizeof(char) * 11);
然后,就去做
snprintf(str, 11, "%10s", name);
使用 snprintf()
而不是 sprintf()
将防止溢出,并且 %10s
将根据需要填充结果字符串。
关于c - 如何在c中按char复制字符串char?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21963633/