[英]How to properly allocate memory to double pointer?
I have this function:我有这个 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.我需要为
array
数组分配 memory 并填充它。
And when I assign *array[i] = s
on the second iteration of the cycle there is Segmentation Fault
.当我在循环的第二次迭代中分配
*array[i] = s
时,就会出现Segmentation Fault
。 (I know that s
is correct). (我知道
s
是正确的)。
How to properly allocate memory to array
in the 3rd line and assign variable in 6th line?如何将 memory 正确分配到第 3 行的
array
并在第 6 行分配变量?
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).如所写,
marray_read
只有在传递一个已经存在的数组时才能工作(通过在array
参数中传递此类数组的第一个元素的地址)。 This is because the use of array[i]
requires that array
be a pointer to the first of several elements.这是因为使用
array[i]
要求array
是指向几个元素中的第一个的指针。
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.您可能打算将
array
参数指向一个指针,该指针将填充为size_t
对象数组分配的 memory 的地址。 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.虽然参数声明
size_t *array[]
和size_t **array
对于编译器来说实际上是相同的,但前者错误地向读者表示array
旨在指向size_t *
对象数组的(第一个元素)。 The latter is what is usually used for a pointer to a pointer to the first element of an array of size_t
objects.后者通常用于指向
size_t
对象数组的第一个元素的指针。
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[i]
是错误的,因为array[i]
是在*
之前处理的,因此它会尝试访问不存在的数组元素。 (*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)
.必须使用
(*array)
以便首先读取array
中的指针,然后(*array)[i]
计算数组中从(*array)
开始的元素的地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.