Jester Jeffrey
Jester Jeffrey

Reputation: 115

Copying an Array of Doubles and then Returning a Pointer to the Base

I've been presented with a task and am having difficulty completing it. Essentially I am to create a function that copies an array of doubles, allocating enough memory, and then returns a pointer to the base of the new array. I've tried various things but don't believe I've got things right yet...

This is what I have so far:

int *arrayCopyAndBase(double *array, int size)
{
    int i;
    int *arrayCopy;
    array_copy = malloc(size * sizeof(int));
    for (i = 0; i < size; i++)
    {
         arrayCopy[i] = array[i];
    }
    return &arrayCopy;
}

Errors I'm sure are obvious but as a beginner I'm struggling to spot them. I know &arrayCopy should probably be &arrayCopy[0] but that results in an ever changing address. Any help appreciated; just needing to get on the right track.

Upvotes: 0

Views: 52

Answers (3)

Harry K.
Harry K.

Reputation: 13

when you use malloc, it returns a void pointer, you need to type cast it as a double.

Upvotes: 0

Tushar
Tushar

Reputation: 8049

Your return statement is incorrect. Currently, you're returning a pointer to an array of ints (int**), when you actually want to return an array of ints (int*). I'm surprised your compiler wasn't complaining about this (or maybe it was, but you didn't mention it).

Try:

return arrayCopy;

Upvotes: 1

Eric Urban
Eric Urban

Reputation: 3820

Several problems:

You're using sizeof(int). You're allocating an array of doubles. Ints are not the same thing as doubles.

arrayCopy is a pointer to an integer. This should be a pointer to a double

You are returning a pointer to a int. You should be returning a pointer to a double.

The return statement takes the adress of a pointer. You only need to return the value of the pointer.

You don't need the for loop. Using memcpy is much more sensible.

Upvotes: 1

Related Questions