我必须完成的练习内容如下:
That
array_remove
function must remove from the arrayarr
the value, that is in the positionpos
, and scale of a position successive values ofpos
, and eventually change the array size for no gaps. If this value is not included in the array (ifpos
is greater thanpn
(array size)), then you should not do anything.
我的问题是:
使用malloc函数可能非常错误,因为执行时会显示以下错误:
MAIN.C:
#include "array.h"
int main(void)
{
double arr[] = { 1.0,2.0,3.0,4.0,5.0 };
size_t pn = 5;/*array length*/
size_t pos = 2;/*position of the number to be deleted*/
array_remove(arr, &pn, pos);
}
数组.C:
#include "array.h"
void array_remove(double *arr, size_t *pn, size_t pos)
{
int x = *pn;
int y = pos;
if (x > y)
{
for (int i = y; i < x; i++)
{
arr[i] = arr[i + 1];
}
realloc(&arr, sizeof(double) * 4);
}
}
最佳答案
根据 C 文档:
realloc Reallocates the given area of memory that must be previously allocated by malloc(), calloc() or realloc() and not yet freed with free, otherwise, the results are undefined.
当您尝试访问arr[i+1] = arr[x=pn]时
:i=x-1
,您在以下几行也遇到了越界问题
for (int i = y; i < ; i++) {
arr[i] = arr[i + 1];
查看以下代码 *(live: https://ideone.com/mbSzjL
#include<stdlib.h>
void array_remove(double **arr, int *pn, int pos) {
int x = *pn;
int y = pos;
if (x > y) {
//check if after deletion size is zero!
if (x > y) {
for (int i = y; i < x-1; i++) {
(*arr)[i] = (*arr)[i + 1];
}
*arr=realloc(*arr, sizeof(double) * x-1);
*pn=*pn-1;
}
}
}
int main(void) {
int pn = 20;/*array length*/
int pos = 5;/*position of the number to be deleted*/
double *arr = malloc(sizeof(double)*pn);
printf("%p\n",arr);
for(int i=0;i<pn;i++){
arr[i] = i;
}
for(int i=0;i<pn;i++){
printf("%.f ",arr[i]);
}
printf("\n");
printf("%i\n",pn);
array_remove(&arr, &pn, pos);
printf("%p\n",arr);
for(int i=0;i<pn;i++){
printf("%.f ",arr[i]);
}
printf("\n");
printf("%i",pn);
free(arr);
}
不要忘记使用正确的大小重新分配(不使用硬编码的 4)并检查删除后大小为零的边缘情况!
此外, 最后释放内存并更新大小变量。
关于c - 重新分配 double 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35335961/