【问题标题】:Using malloc to create a string containing elements from another string in c使用 malloc 创建一个字符串,其中包含 c 中另一个字符串中的元素
【发布时间】: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--;在打印之前的循环中。但同样的问题仍然存在。

标签: c string pointers malloc


【解决方案1】:

我不明白为什么这不会打印“aabbcc”

它不会这样做有两个原因:

  • 您没有传递指向字符串开头的指针,并且
  • 因为您没有添加空终止符

要解决第一个问题,请在执行增量之前将指向分配给newstr 的块的指针存储在临时位置。

要解决第二个问题,请在循环后添加*newstr = '\0',并调整malloc 调用以为终止符添加额外的char

// Do not multiply by sizeof(char), because the standard requires it to be 1
// You used sizeof(char*), which is wrong too.
char * newstr = malloc((count * 2) + 1);
char *res = newstr; // Store the original pointer
// Your implementation of the actual algorithm looks right
while (...) {
    ... // Do the loop
}

*newstr = '\0';
printf("%s\n", res); // Pass the original pointer

【讨论】:

  • 还有两件事,他忘记了第二个newstr++,也没有必要取消引用*newstr++(在OP代码示例处)。
【解决方案2】:

你的循环前进newstr,所以在它完成后,它不再指向字符串的开头。您需要保存原始指针以用于打印。

【讨论】:

    【解决方案3】:

    从这一行开始

    char * newstr = malloc(sizeof(char *) * (count * 2)); 
    

    应该是

    char * newstr = malloc(1 + (count * 2));
    

    包含空字符

    那你忘记添加了

    还有newstr指向新字符串的末尾

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-26
      • 2012-11-21
      • 2016-02-23
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      相关资源
      最近更新 更多