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).
b[i] = a[i];— if you don't usememmove()ormemcpy().