C 函数将数组的一部分 memcpy 到数组的另一个重新分配的部分

发布于 2025-01-16 12:58:40 字数 1468 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪痕残 2025-01-23 12:58:44

首先,您在计算 k 时遇到问题:

  1. i 的增量放入 for 标头中。在 if 语句中执行此操作很令人困惑 - 起初我以为您有一个无限循环,因为您没有递增。
  2. 当条件失败时跳出 for 循环。
  3. arr[i] 应该是 (*arr)[i​​]
  4. 您需要初始化 k = 1 以便计算第一组中的最后一个元素。

由于 memcpy() 不允许源和目标重叠,因此您应该加倍分配,而不是仅仅添加足够的 k 元素。复制整个数组,然后按重新排列的顺序将各部分复制回开头。

int arrangeArray(int** arr, int n)
{
    // your code:
    int k = 1, rest;
    for (int i = 0; i < n-1; i++)
    {
        if ((*arr)[i] < (*arr)[i+1]) {
            k++;
        } else {
            break;
        }
    }
    rest = n - k;
    *arr = realloc(*arr, 2 * n * sizeof(int)); // reallocate to double the size
    memcpy((*arr)+n, *arr, n*sizeof(int)); // duplicate the array
    memcpy(*arr, *arr + n + k, rest * sizeof(int)); // copy the rest to the beginning
    memcpy(*arr + rest, *arr + n, k * sizeof(int)); // copy the beginning to the end
    *arr = realloc(*arr, n * sizeof(int)); // reallocate back to the original size
    return k;
}

First, you have a problem with your calculation of k:

  1. Put the increment of i in the for header. It's confusing to do it in the if statement -- at first I thought you had an infinite loop because you weren't incrementing.
  2. Break out of the for loop when the condition fails.
  3. arr[i] should be (*arr)[i].
  4. You need to initialize k = 1 so that the last element in the first group is counted.

Since memcpy() doesn't allow overlapping source and destination, you should double the allocation, rather than just adding enough for k elements. Duplicate the entire array, then copy the portions in the rearranged order back to the beginning.

int arrangeArray(int** arr, int n)
{
    // your code:
    int k = 1, rest;
    for (int i = 0; i < n-1; i++)
    {
        if ((*arr)[i] < (*arr)[i+1]) {
            k++;
        } else {
            break;
        }
    }
    rest = n - k;
    *arr = realloc(*arr, 2 * n * sizeof(int)); // reallocate to double the size
    memcpy((*arr)+n, *arr, n*sizeof(int)); // duplicate the array
    memcpy(*arr, *arr + n + k, rest * sizeof(int)); // copy the rest to the beginning
    memcpy(*arr + rest, *arr + n, k * sizeof(int)); // copy the beginning to the end
    *arr = realloc(*arr, n * sizeof(int)); // reallocate back to the original size
    return k;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文