The function is not simple as it seems at first glance.
Here you are.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
typedef struct
{
int *tab;
int size;
} arr;
int changeSizeDyn( arr *Dyn_arr, int size )
{
int success = 1;
if ( Dyn_arr->size != size )
{
int *tmp = NULL;
if ( size != 0 )
{
tmp = malloc( size * sizeof( int ) );
success = tmp != NULL;
if ( success )
{
int n = 0;
if ( Dyn_arr->size != 0 )
{
n = size < Dyn_arr->size ? size : Dyn_arr->size;
memcpy( tmp, Dyn_arr->tab, n * sizeof( int ) );
}
if ( n < size ) memset( tmp + n, 0, ( size - n ) * sizeof( int ) );
}
}
if ( success )
{
free( Dyn_arr->tab );
Dyn_arr->tab = tmp;
Dyn_arr->size = size;
}
}
return success;
}
int main( void )
{
arr a = { NULL, 0 };
int size = 10;
if ( changeSizeDyn( &a, size ) )
{
for ( int i = 0; i < size; i++ ) a.tab[i] = i;
for ( int i = 0; i < size; i++ ) printf( "%d ", a.tab[i] );
putchar( '\n' );
}
size = 5;
if ( changeSizeDyn( &a, size ) )
{
for ( int i = 0; i < size; i++ ) a.tab[i] = i;
for ( int i = 0; i < size; i++ ) printf( "%d ", a.tab[i] );
putchar( '\n' );
}
size = 0;
if ( changeSizeDyn( &a, size ) )
{
for ( int i = 0; i < size; i++ ) a.tab[i] = i;
for ( int i = 0; i < size; i++ ) printf( "%d ", a.tab[i] );
putchar( '\n' );
}
assert( a.tab == NULL && a.size == 0 );
}
The program output is
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4
The function has a return type int
to signal whether its call was successful or not. You need a method to determine whether a function call was successful. Otherwise it will be impossible to determine this. So to use the type void
as the return type of the function is a bad idea.
The function by default sets all new elements that do not correspond to the elements of the old array to zero. In fact it is not necessary but makes the usage of the structure more clear.
If the user passes the size equal to 0 then the function just free the old array and sets the data member tab
to NULL
.
If the new size and old size of the array are equal each other the function does nothing.
Take into account that it is much better to declare the data member size
of the structure as having type size_t
. Otherwise you need to add a check in the function that size
is not negative. I did not do that because I suppose that you will indeed use the type size_t
instead of the type int
in the structure (and function) declaration.