【问题标题】:function that takes user input and adds it to an array接受用户输入并将其添加到数组中的函数
【发布时间】:2012-03-14 17:19:12
【问题描述】:

我有一个作业问题来完成这个方法。我真的不知道该怎么办。鉴于这个伪代码有人可以帮我写这个方法吗?

/*
    make a new array of the old size plus the new size
    copy from the old to the new
    add the new characters
    don't forget to clean up the old array (free it)
    before you leave this function
*/

char * add(char * array, int num)
{
    return array;

}

【问题讨论】:

  • 不清楚新尺寸是多少?也许这也需要作为函数参数传递?要添加到新数组中的新字符是什么?
  • 你的函数签名必须是char * add(char * array, int num)吗?
  • 是的,它必须有那个签名

标签: c arrays


【解决方案1】:

由于这是 C,请查看 realloc - 但您还需要为旧大小设置一个参数(或者可能使用 strlen

【讨论】:

    【解决方案2】:

    这是一个伪代码:

    char * add(char * old_array, int old_size, char *additions, int new_size)
    {
        malloc new_size bytes and assign to new_array
        memcpy old_size bytes from old_array into the new_array
        add additions into new_array starting from (new_array+old_size)
        free the old_araray
        return new_array;
    
    }
    

    【讨论】:

    • @EdHeal,来自 OP “不要忘记清理旧数组(释放它)”
    • realloc 为您整理复制和释放(如果需要)。
    • 给老师两个解决方案,并指出我们的 relloc 会是一个更好的方法 - 因为它会更快
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多