将realloc与指针到指针任务一起使用



我在任何任务中都会练习我的c技能。我把这个练习叠加起来:我在一个数组中有两个阶数组,第一个数组中的第一个元素比第一个数组的最后一个元素大。我只需要使用realloc((和memcpy对数组进行排序(不使用malloc/new数组(。并返回第一数组的大小-K。(0<=k<n(。函数获取指向n个数字的动态数组的指针的地址。

对于exe:{32,64,66,69,7,78,81,87,94,95,1,2,4,8,17}

我对指针的realloc((有一个小问题。我试着将数组放大到第一个数组的大小,将第一部分复制到数组的末尾,然后将第二部分复制到开头,然后将最后一个部分复制到下一个部分,然后再将realloc((复制到更大的大小。

我的代码到现在为止:

int arrangeArray(int** arr, int n)
{
int i = 0;
int first_size;
int second_size;
int new_size;
while (*(*arr + i) < *(*arr + i + 1)) { // find the size of the first array 
num = *(*arr + i + 2);
i++;
}
first_size = i + 1;;
second_size = n - i;
new_size = n + first_size;
*arr = (int*)realloc(*arr, new_size * (sizeof(int))); // enlarge the size of the array;
memcpy((*arr) + n, (*arr), sizeof(int) * first_size); // copy the first part to the end of the array;
memcpy((*arr), (*arr) + first_size, sizeof(int) * second_size); // copy the second array to the first of the new;
memcpy((*arr) + second_size - 1, *arr + n, sizeof(int) * first_size); // copy the last array to the last;
*arr = (int*)realloc(*arr, (n * (sizeof(int)))); // resize to the orginal size;
return first_size;
}

您使用malloc、free、realloc等与"指向T"的指针;,其中T是任何类型。在您的情况下,T=int*,这可能会令人困惑,但没有什么特别之处

对于一个有n个元素的数组,您可以编写

T* array = (T*) malloc(n * sizeof (T))

T* array = (T*) calloc (n, sizeof (T)). 

要重新分配数组,您有两种选择:要么祈祷realloc永远不会失败,要么编写代码来处理失败。一种处理方法:

T* array = ...; // This is where you created and filled the array
T* oldArray = array;
array = (T*) realloc (array, n * sizeof (T));
if (array == NULL) {
// realloc failed, oldArray contains the original data.
// Do what you can to handle the failure
array = oldArray;
return;
}
// Now you are NOT allowed to use oldArray anymore. It's only valid if
// realloc failed. 

需要记住的两件事是:如果你真的在缩小数组,你必须在realloc之前将元素与你想在最后丢弃的元素重新排列。但是,如果您缩小数组,那么realloc可能会失败!在这种情况下,您将继续使用原始数组。而且它可以(而且经常(返回与原始指针不同的指针。

如果使数组变大,并且realloc没有失败,那么新数组将从原始数据开始,然后是垃圾。

请注意,您必须始终自己跟踪数组大小。正如注释中提到的,sizeof返回指针的大小,因此很可能是4或8,而不是分配的内存的大小。

请不要在指针运算中使用加法+解引用。写a[i]比写*(a + i)可读得多。

最新更新