c - 重新分配 C 数组以获得更多空间

标签 c arrays pointers realloc

我正在编写一个带有函数 add(a , i, n) 的程序,该函数会将 'i' 作为元素添加到 'a' 中,但是如果数组 'a' 空间不足,那么我需要重新分配更多空间内存到数组。我被困在这里:

#include <stdlib.h>
#include <stdio.h>

int add(int* a, int i, int n);

int main(){
    int n = 20;
    int *a = (int*) malloc(n*sizeof(int));
    int i;

    for (i = 0; i < 100000; i++){
        n = add(a, i, n);
        printf("a[%d]=%d\n",i,(int)a[i]);
    }
    return 0;
}

int add(int *a, int i, int n){
    if (i >= n){
        n++;
        int* b = (int*) realloc(a, n*sizeof(int));
        a[i]=i;
        return n;
    }else{
    }
}

我经验不足,所以请温柔一点......

最佳答案

realloc 尝试重新分配给定的内存,但有时它不能,并且会为您提供一个新的内存指针。

它的使用方式必须如下:

int *b;
b = realloc(a, <newsize>);
if (b) {
    /* realloc succeded, `a` must no longer be used */
    a = b;
    /* now a can be used */
    printf("ok\n");
} else {
    /* realloc failed, `a` is still available, but it's size did not changed */
    perror("realloc");
}
<小时/>

现在,您的代码仍然存在一些问题:

函数add()的思想是在需要时重新分配a,但是a是通过copy给出的,所以它的值不会'不能在 main 中更改。

#include <stdlib.h>
#include <stdio.h>

int add(int** a, int i, int n);

int main(){
    int n = 20;
    int *a = malloc(n*sizeof(int));
    int i;

    for (i = 0; i < 100000; i++) {
        /* note how `a` is passed to `add` */
        n = add(&a, i, n);
        printf("a[%d]=%d\n",i,a[i]);
    }
    /* and finally free `a`*/ 
    free(a);
    return 0;
}

/* changed `a` type to make its new value visible in `main` */
int add(int **a, int i, int n){
    if (i >= n){
        /* want to write a[i], so size must be at least i+1*/
        n = i+1;
        /* realloc memory */
        int *b = realloc(*a, n*sizeof(int));

        /* check that `realloc` succeded */
        if (!b) { 
            /* it failed!*/
            perror("realloc"); 
            exit(1);
        } 
        /* store new memory address */
        *a = b;
    }

    /* update memory */        
    (*a)[i]=i;        

    /* return new size */
    return n;
}
<小时/>

注意:我删除了 malloc/realloc 转换,请参阅:Do I cast the result of malloc?

关于c - 重新分配 C 数组以获得更多空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51258722/

相关文章:

php - 将多维数组变成一维数组

c# - 将数组发送到 ASMX WebService 时出错

c++ - 如何通过基类指针调用派生类的虚函数

C语言: How to use memset to reset dynamic 2d array?

java - codechef 和 spoj 问题中使用模 10^9+7 的意义是什么?

c - 通过 Eclipse CDT 传递参数

创建结构数组

java - 通过 JNI 在 C 和 Java 之间传递指针

c++ - 引用或复制结构的结构(分配了 memset)是有效的事情吗?

c - 使用 dub2() 将输出重定向到文件 : undefined reference to `dub2'