Each of the following program segments might
have syntax, logic or other kinds of errors. If there are errors,
correct, otherwise answer "no error". Assume all function headers
are correct.
Function copy_array receives an integer array a and
its size length, as parameters. It copies the array a into
another integer array b newly created, and returns the address
of the new array b.
int *copy_array ( int a[], int length )
{
int i;
int b[length];
for (i =0; i <= length, i++ )
b[i] = a[i];
return b[0];
}
CORRECT:
int *copy_array ( int a[], int length )
{
int i;
int *b = calloc( length, sizeof(int)); [B]line 1[/B]
/* or int *b = malloc( length * sizeof(int)); */ [B]line 2[/B]
for (i =0; i < length; i++ )
b[i] = a[i];
return b;
/* or return &b[0] */
}
My Question is that is dynamic memory allocation really necessaryÉ since you already know the size of the array which is being passed by the caller. Also can some someone explain each step of line 1 and 2. Thanks in advance.