【发布时间】:2014-06-07 20:06:19
【问题描述】:
在 C 中创建一个以字符串为参数的函数,并将其复制到新字符串中。 如果原始字符串是“abc”,那么新字符串应该是“aabbcc”,如果原始字符串是“4”,那么新字符串应该是 44 等等。我相信我理解解决此类问题所需的概念,但我只是无法在控制台中打印新字符串。这是我的功能:
void eco(char * str)
{
int count = 0;
/*Counts the number of symbols in the string*/
while(*(str + count) != '\0')
{
count++;
}
/*Memory for the new string, wich should be 6 chars long ("aabbcc").*/
char * newstr = malloc(sizeof(char *) * (count * 2));
/*Creating the content for newstr.*/
while(count > 0)
{
*newstr = *str; //newstr[0] = 'a'
*newstr++; //next newstr pos
*newstr = *str; //newstr[1] = 'a'
*str++; //next strpos
count--;
}
/*I can't understand why this would not print aabbcc*/
printf("%s", newstr);
/*free newstr from memory*/
free(newstr);
}
我尝试在为newstr创建内容的while循环中单独打印每个字符,并且工作正常。但是当我尝试使用“%s”标志时,我要么得到奇怪的非键盘符号,要么什么都没有。
【问题讨论】:
-
请修复代码标识!
-
不要忘记分配空间并初始化 0 以终止字符串。
-
malloc(sizeof(char *)几乎肯定不是你想要的。 -
另外,您正在修改
newstr的值,以便在您要显示它时不再指向字符串的开头。 -
我尝试在 malloc 中为 '\0' 添加一个额外的字符,并且我尝试使用 newstr--;在打印之前的循环中。但同样的问题仍然存在。