初始化扩展数组元素

发布于 2024-10-31 19:04:46 字数 319 浏览 3 评论 0原文

所以我已经能够学习扩展数组,但想知道如何将元素添加到扩展的空间中,这是我到目前为止所拥有的。

int *expand(int *arr, int size)
{
    int *newArray;


    newArray = new int[size * 2];
    memcpy( newArray, arr, size * sizeof(int));
    for (int index = 5; index < size; index++)
        newArray[index] = 0;
    return newArray;

}

So i've been able to learn to expand an array, but was wondering how i would go about adding elements to the expanded space, here is what i have so far.

int *expand(int *arr, int size)
{
    int *newArray;


    newArray = new int[size * 2];
    memcpy( newArray, arr, size * sizeof(int));
    for (int index = 5; index < size; index++)
        newArray[index] = 0;
    return newArray;

}

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

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

发布评论

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

评论(1

夜深人未静 2024-11-07 19:04:46

我认为您的代码中可能存在错误。 newArray 的大小为“size * 2”,但您只能初始化“size”之前的元素。

试试这个:

newArray = new int[size * 2];
memcpy( newArray, arr, size * sizeof(int));
for (int index = size; index < (size*2); index++)
    newArray[index] = 0;
return newArray;

这应该将新空间中的所有元素初始化为 0。

I think you might have a bug in your code. newArray is of size "size * 2", but you initialize elements only up until "size".

Try this:

newArray = new int[size * 2];
memcpy( newArray, arr, size * sizeof(int));
for (int index = size; index < (size*2); index++)
    newArray[index] = 0;
return newArray;

This should initialize all the elements in the new space to 0's.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文