Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将动态数组传递给C中的函数_C_Arrays_Dynamic_Parameter Passing_Pass By Pointer - Fatal编程技术网

将动态数组传递给C中的函数

将动态数组传递给C中的函数,c,arrays,dynamic,parameter-passing,pass-by-pointer,C,Arrays,Dynamic,Parameter Passing,Pass By Pointer,我试图通过编写简单的代码片段来学习指针。我今天写了以下内容 #include <stdio.h> #include <stdlib.h> void funcall1(int *arr_p, int *num_elements_p) { int i = 0; *num_elements_p = 10; int *temp = (int *)malloc(10 * sizeof(int)); if (temp != NULL) { arr_p =

我试图通过编写简单的代码片段来学习指针。我今天写了以下内容

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

void funcall1(int *arr_p, int *num_elements_p)
{
  int i = 0;
  *num_elements_p = 10;
  int *temp = (int *)malloc(10 * sizeof(int));
  if (temp != NULL)
  {
    arr_p = (int *)temp;
  }
  else
  {
      free(arr_p);
      printf("Error\n");
      return;
  }
  printf("\n------------------------funcall1------------------------------\n");
  for (i=0; i<(*num_elements_p); i++)
  {
      arr_p[i]= i;
      printf ("%d\t", arr_p[i]);
  }

}
int main()
{
  int *arr = NULL;
  int num_elements = 0;
  int i = 0;
  /*int *temp = (int *)malloc(10 * sizeof(int));
  if (temp != NULL)
  {
      arr = (int *)temp;
  }
  else
  {
      free(arr);
      printf("Error\n");
      return;
  }*/

  funcall1(arr, &num_elements);
  printf("\n------------------------Main------------------------------\n");
  for (i=0; i<num_elements; i++)
  {
    printf ("%d\t", arr[i]);
  }
  printf ("\n");
  free(arr);
  return 0;
}
当我在主函数中使用malloc时,代码按预期工作;但是当我在被调用函数中使用它时,它没有,我得到了分段错误。我做了一些研究,了解了一些基本知识,比如, 1.数组名实际上是指向数组中第一个元素的指针。因此,我正确地传递了参数。 2.数组得到更新,因为我也在被调用函数中打印数组


因为arr_p实际上指向arr指向的地方,当我做arr_p=int*temp时,它不是意味着,arr也指向这个分配的内存空间吗?我在寻找内存中发生了什么,为什么我会在这里遇到内存访问冲突?我不想用一些部分推导出来的假设来说服自己。

C是通过价值传递的。进一步澄清一下,arr\u p与arr不同;当你给arr\u p赋值时,arr仍然指向它之前指向的东西。因为arr\u p实际上指向arr指向的地方。。。这样想吧。你拿INTI。你过了5级。既然它们有相同的值,那么应该做i=6;更改原始值?@SaranyaDeviGanesan,指针按值传递。它存储相同的地址。您可以使用该地址间接访问int。因为arr_p实际上指向arr指向的位置,所以当我执行arr_p=int*temp时。。。你刚刚扔掉了这个地址,这句话的第一部分是真的。