-1

I have this function:

void marray_read( size_t* size, size_t* array[] ) {
    *size = read_size();
    *array = malloc(sizeof(size_t) * *size);
    for (size_t i = 0; i < *size; i++) {
        size_t s = read_size();
        *array[i] = s;
    }
}

I need to allocate memory for array array and fill it.

And when I assign *array[i] = s on the second iteration of the cycle there is Segmentation Fault. (I know that s is correct).

How to properly allocate memory to array in the 3rd line and assign variable in 6th line?

1 Answers1

0

As written, marray_read could work only if it is passed an array that already exists (by passing the address of the first element of such an array in the array parameter). This is because the use of array[i] requires that array be a pointer to the first of several elements.

You may have intended to the array parameter to point to a pointer that will be filled in with the address of memory allocated for an array of size_t objects. In this case, the array declaration should be:

void marray_read(size_t *size, size_t **array)

and this line:

*array[i] = s;

should be:

(*array)[i] = s;

While the parameter declarations size_t *array[] and size_t **array are effectively the same for the compiler, the former incorrectly expresses to the reader that array is intended to point to (the first element of) an array of size_t * objects. The latter is what is usually used for a pointer to a pointer to the first element of an array of size_t objects.

The prior code *array[i] is wrong because array[i] is processed before *, so it attempts to access elements of an array where there is none. (*array) must be used so that the pointer at array is read first, and then (*array)[i] calculates the address of an element in an array that starts at (*array).

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312