简体   繁体   中英

Copying Array Using Pointers

I am trying to create a copy of an array by only accessing an array using pointer arithmetic. This is my function

 int* arrCopy(int *a, int size){
    int *b = (int*)malloc(size*sizeof(int));
    for(int i = 0; i < size; i++){
        *(b+(sizeof(int)*i)) = *(a+(sizeof(int)*i));
    }
    return b;
}

When I print the array it shows that the copied array is filled with the repeating of the first two values in the original array. So if the original array was [1, 2, 3, 4, 5], then arrcopy would be [1, 2, 1 ,2 ,1] and I can't figure out why.

Here you are

int * arrCopy( const int *a, size_t n )
{
    int *b = malloc( n * sizeof( int ) );

    for ( size_t i = 0; i < n; i++ )
    {
        *( b + i ) = *( a + i );
    }

    return b;
}

Or you could check whether the memory was successfully allocated.

int * arrCopy( const int *a, size_t n )
{
    int *b = malloc( n * sizeof( int ) );

    if ( b != NULL )
    {
        for ( size_t i = 0; i < n; i++ )
        {
            *( b + i ) = *( a + i );
        }
    }

    return b;
}

Here is a demonstrative program

#include <stdio.h>
#include <stdlib.h>

int * arrCopy( const int *a, size_t n )
{
    int *b = malloc( n * sizeof( int ) );

    if ( b != NULL )
    {
        for ( size_t i = 0; i < n; i++ )
        {
            *( b + i ) = *( a + i );
        }
    }           

    return b;
}

int main(void) 
{
    int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    const size_t N = sizeof( a ) / sizeof( *a );

    int *b = arrCopy( a, N );

    if ( b != NULL )
    {
        for ( size_t i = 0; i < N; i++ )
        {
            printf( "%d ", b[i] );
        }

        putchar( '\n' );
    }

    free( b );

    return 0;
}

Its output is

0 1 2 3 4 5 6 7 8 9

As for your code then for example this expression

*(b+(sizeof(int)*i))

is invalid. It selects the element of the array b equivalent to

b[sizeof(int)*i]

So for example when i is equal to 1 and sizeof( int ) equal to 4 then instead of getting the element b[1] you are getting the element b[4] .

From the C Standard (6.5.2.1 Array subscripting)

2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM