开发者

Initializing an expanded array elements

开发者 https://www.devze.com 2023-02-24 12:26 出处:网络
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.

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++)
        new开发者_如何学JAVAArray[index] = 0;
    return newArray;

}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号