这在主要方面起作用,但是在放入函数时会中断。我不确定传递给函数后如何重新分配指针。
void expandArray(int** arr[], int* size) {
int *temp;
*temp = *arr;
*arr = (int*) malloc(*size * 2 * sizeof(int));
for (int i = 0; i < *size; i++) {
printf("assigning from temp: %d ", temp[i]);
arr[i] = temp[i];
printf("to arr: %d \n", arr[i]);
}
*size = *size * 2;
free(temp);
}
main(){
int *arr;
arr = (int*) malloc(maxSize * sizeof(int));
if ....
expandArray(arr, &arrSize);
// use bigger arr for other stuff
}
在中main
,arr
声明为int *arr
。当main
调用expandArray
,它应该通过一个指针arr
,写的是&arr
,有型int **a
。
但是,您将参数声明expandArray
为int **arr[]
,添加了方括号。这些都是不必要的,并且可以更改类型,并且您的编译器应该已经对此发出警告。注意编译器警告。在继续操作之前,请确保您了解它们并解决它们。
在中expandArray
,您可以同时使用arr[i]
和temp[i]
访问该数组。但是,arr[i]
这不是访问数组元素的正确方法。arr
更正参数的声明后,它将是int **arr
,并且将数组的元素引用为不合适arr[i]
。会的(*arr)[i]
。
通常,为了减少混淆,作者将使用一个临时变量来保存指针,因此他们不需要多余的星号:
int *NewArray = malloc(...); // Get new space.
*arr = NewArray; // Send new address to caller.
...
NewArray[i] = temp[i]; // Use temporary variable for access.
其他一些要点:
malloc
,请使用,而不是,将指针分配到了sizeof *p
哪里。这样比较好,因为如果以后要更改其类型,则只需在其声明中进行更改,而不必在中进行更改。这样一来,在一个地方而不是另一个地方进行更改的可能性就很小。p
sizeof(int)
p
sizeof
malloc
。尽管在C ++中是必需的,但这在C中是不必要的。main
应声明为int main(void)
或int main(int argc, char *argv[])
,而不应声明为main()
。(C实现也可以提供其他形式。)size_t
数组的大小,而不是int
和两种size_t
或ptrdiff_t
数组的索引。总体而言,代码可能是:
#include <stdio.h>
#include <stdlib.h>
void expandArray(int **arr, int *size)
{
// Record old pointer and size in temporary variables for convenience.
int *OldArray = arr;
size_t OldSize = *size;
// Prepare new size and pointer.
size_t NewSize = 2 * OldSize;
int *NewArray = malloc(NewSize * sizeof *NewArray);
// Handle allocation failure.
if (!NewArray)
{
fprintf(stderr, "Error, unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
// Copy data from old array to new array.
for (size_t i = 0; i < OldSize; ++i)
NewArray[i] = OldArray[i];
// Send new size and pointer to caller.
*size = NewSize;
*arr = NewArray;
// Release old memory.
free(OldArray);
}
int main(void)
{
int *arr;
arr = malloc(InitialSize * sizeof *arr);
if (...)
expandArray(&arr, &arrSize);
// use bigger arr for other stuff
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句