简体   繁体   English

将数组指针传递给函数,然后重新分配数组并在 C 中更改其值

[英]Passing an array pointer to a function and then reallocating the array and changing its values in C

I have a pretty basic question, I tried to answer it for many hours now but it still doesn't work.我有一个非常基本的问题,我试图回答它好几个小时,但它仍然不起作用。 I want to malloc an array in main, pass it to another function, reallocate it and then change it's values.我想在 main 中分配一个数组,将它传递给另一个函数,重新分配它,然后更改它的值。 Why does the following code work:为什么以下代码有效:

void fun(int **array, int *size) {
    *array = (int *) realloc(*array, *size * sizeof(int));
    *array[0] = 1;
  
    return;
}

int main() {
    int size = 5;
    int *array = (int *) malloc(2 * sizeof(int));
    fun(&array, &size);
  
    return 0;
}

... but as soon as I try to change array[1] like this: ...但是一旦我尝试像这样更改数组[1]:

void fun(int **array, int *size) {
    *array = (int *) realloc(*array, *size * sizeof(int));
    *array[0] = 1;
    *array[1] = 2;

    return;
}

int main() {
    int size = 5;
    int *array = (int *) malloc(2 * sizeof(int));
    fun(&array, &size);
  
    return 0;
}

... it doesn't work anymore. ......它不再起作用了。 It gives me segmentation fault and invalid write of size 4 .它给了我分段错误大小为 4 的无效写入

In *array[0] = 1;*array[0] = 1; , the [] operator has highest precedence, meaning it's interpreted as first doing pointer arithmetic on a int** , then de-reference it. []运算符具有最高优先级,这意味着它被解释为首先对int**进行指针运算,然后取消引用它。 It's equivalent to **(array + 0) = 1 which is not what you want.它相当于**(array + 0) = 1这不是你想要的。

For a single-dimension array you can simply do this:对于单维数组,您可以简单地执行以下操作:

#include <stdlib.h>

void fun (int** array, int size)
{
  int* tmp = realloc( *array, sizeof(int[size]) );
  if(tmp == NULL)
  {
    // error handling here
  }
  *array = tmp;

  (*array)[0]=1;
  (*array)[1]=2;
}

int main (void)
{
  int* array = malloc(2*sizeof *array);
  int size = 5;
  fun(&array, size);

  free(array);
  return 0;
}

For multiple dimensions, check out Correctly allocating multi-dimensional arrays对于多维,请查看正确分配多维数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM