【问题标题】:pointer of a pointer and memory allocation指针的指针和内存分配
【发布时间】:2018-01-09 18:18:14
【问题描述】:

如果我有int **array 并想在其中放置一系列数字(我不知道它的大小),以5 3 4 09 1 5 8 3 0 为例。据我所知,我应该使用malloc

所以我做了这样的事情

int **array;
int n = 1, inp = 0;
while(n){ // scan till the input is 0
    scanf("%d", &n);
    array = (int**)malloc(sizeof(int*)*(inp+1)); //since inp start at 0
    array[inp] = &n; //is this even correct?
    inp++;
}

我的第一个问题是:这个方法(循环)会升级/扩展array 的大小还是我在做什么浪费内存?

第二个问题是如何打印/编辑这个array 的值?

编辑:

根据您的回答,我得出以下结论。

int **array;
int n = 1, inp = 0;
array = (int**)malloc(sizeof(int*));
while(n){
    scanf("%d", &n);
    realloc( array, sizeof((int*)(inp+1)));
    array[inp] = n;
    inp++;
}

这是正确的做法吗?

注意*我知道它不一定是指针的指针,但我需要它稍后用于其他东西。

【问题讨论】:

  • 这个数组[inp] = &n;没有意义,因为数组的所有元素都将具有相同的值:变量 n 的地址。
  • 为什么是双指针?你不只是想要一个一维整数数组吗?不,循环内的 malloc 是个坏主意。 realloc 更好。
  • 不要为此使用malloc - 这都是错误的。使用realloc
  • ... 和一个初始值为 NULL 的指针。
  • @LeeDanielCrocker 我稍后会添加更多的一维数组。

标签: c arrays pointers malloc


【解决方案1】:

至少由于这些原因,您的代码是错误的。

1) 你一直在做mallocarray 并因此松散了之前的malloced 块。扩展动态内存大小时使用的函数是realloc

2) 你存储n 的地址而不是n 的值

此外,使用双指针似乎很奇怪。为什么不喜欢:

int *array = NULL;
int n = 1, inp = 0;
while(n){ // scan till the input is 0
    scanf("%d", &n);
    array = realloc(array, sizeof(int)*(inp+1));
    array[inp] = n;
    inp++;
}

OP 更新后编辑

如果真的要使用双指针(即int **array;),则需要分两级分配内存。

可能看起来像:

int **array = malloc(sizeof *array);
*array = NULL;
int n = 1, inp = 0;
while(n){ // scan till the input is 0
    scanf("%d", &n);
    *array = realloc(*array, sizeof(int)*(inp+1));
    (*array)[inp] = n;
    inp++;
}

【讨论】:

    【解决方案2】:

    您在代码中所做的是逐渐分配更大的内存区域并将输入值保存在每个新区域的最后位置,同时丢失指向先前分配区域的指针。对于您想要的东西(我相信在 C++ 的向量中使用),一个通用且有效的解决方案是分配一些最小量的空间,然后在每次迭代时检查您是否处于超出它的边缘。如果是这样,请重新分配使空间翻倍的区域。像这样的:

    int i = 0; //iterator
    int s = 1; //array size
    int n;     //input (use do-while so you don't have to worry about initial value)
    
    //it doesn't have to be bidimensional for a single series
    int * array = (int *) malloc(sizeof(int) * s);
    
    do
    {
        if(i == s)
        {
            s *= 2;
            array = (int *) realloc(array, sizeof(int) * s);
        }
        scanf("%d", &n);
        array[i++] = n; //assign with the value, not with the address
    }
    while(n)
    

    更新:如果你真的需要使用 **int,这样做:

    int n, i = 0, s = 1;
    
    int ** array = (int **) malloc(sizeof(int*) * s);
    
    do
    {
        if(i == s)
        {
            s *= 2;
            array = (int **) realloc(array, sizeof(int *) * s);
        }
        scanf("%d", &n);
        array[i] = (int *) malloc(sizeof(int));
        array[i][0] = n;
        ++i;
    }
    while(n)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 2015-04-21
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      相关资源
      最近更新 更多