c - 重新分配 double 组

标签 c arrays double realloc

我必须完成的练习内容如下:

That array_remove function must remove from the array arr the value, that is in the position pos, and scale of a position successive values of pos, and eventually change the array size for no gaps. If this value is not included in the array (if pos is greater than pn (array size)), then you should not do anything.

我的问题是:

使用malloc函数可能非常错误,因为执行时会显示以下错误:

enter image description here

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)并检查删除后大小为零的边缘情况!

此外, 最后释放内存并更新大小变量。

http://en.cppreference.com/w/c/memory/realloc

关于c - 重新分配 double 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35335961/

相关文章:

php - 解析 JSON 数组 PHP - 字符串和 float

Java代码1+问题

java - 将 double 值转换为文本

ios - 坐标的两位小数

c - 当我用 signal(SIGINT,f) 捕捉到一个信号时,f 是并行执行的吗?

arrays - 在数组的开头插入一个字符串,而不丢失第一个位置的字符串

c - openssl解密找不到和加密前一样的值

java - 如何将浮点值舍入为 double 值?

c - 删除整个链表 C

c - 当对象在内存中移动时,指针如何保持有效?