【问题标题】:Create a Dynamic array (calloc) in a function, and use it in main [duplicate]在函数中创建一个动态数组(calloc),并在 main [重复]
【发布时间】:2019-05-17 17:44:23
【问题描述】:

很抱歉打开一个新问题,但我在论坛或谷歌周围找不到这样的问题..

无论如何,我的问题是: 在 Main 中,我声明了一个数组“insieme_A”和一个包含数组“nums_element_A”长度的变量

int main()
{
     double *insieme_A;
     int nums_element_A;

     nums_element_A = get_array(insieme_A);

然后,打印数组:

 int counter;
 printf("\nL'array è costituito dai seguenti elementi: \n");
 for (counter = 0; counter < nums_element_A; ++counter)
       printf("%lf \n", insieme_A[counter]);` 

然后我有一个函数,由库导出。在这个函数中,我问用户“数组必须有多少个元素?

然后创建动态数组array = (double *)calloc(nums_elements, sizeof (double)); 并用for循环内的元素填充它。

我的问题是函数结束时,我主要尝试打印数组..它打印用户插入的元素数..但全为零。

如果用户想要一个 5 元素数组,它会打印 {0,0,0,0,0}

相反,如果我在函数内打印数组,它可以正常工作。 所以我想知道.. 是否可以这样做,或者我应该将数组写入文件中.. 结束函数并在主文件中打开文件并从那里读取数组?

非常感谢

int get_array(double array[])
{
    double element;
    int nums_elements,
    counter;

     do
     {
         printf("Quanti elementi deve contenere l'insieme? ");
         scanf("%d", &nums_elements);
     }
     while (nums_elements <= 0);

     array = (double *)calloc(nums_elements, sizeof (double));

     for (counter = 0;
          counter < nums_elements;
          ++counter)
     {
         printf("Inserire valore %d-->", counter+1);
         scanf("%lf",
                 &element);
         array[counter] =  element;
     }

     for(counter=0;counter<nums_elements;++counter){
        printf("%lf",array[counter]);
     }

     return (nums_elements);
}

【问题讨论】:

  • 您正在将数组 val 的副本发送到您的 get 函数中-因此您并没有真正修改它在 main 中指向外部的位置-您应该尝试发送 get_array(double *array[ ])

标签: c arrays function pointers dynamic


【解决方案1】:

这是因为在您的代码中,get_array 函数的参数是按值传递的

要更正它,请将其用作 int get_array(double **array) 并相应地更改您的代码。以下是代码 sn-p。 See complete working code here:

int get_array(double **array)
{
    int nums_elements, counter;

    do
    {
        printf("Quanti elementi deve contenere l'insieme? ");
        scanf("%d", &nums_elements);
    } while (nums_elements <= 0);

    *array = (double *)calloc(nums_elements, sizeof (double));

    for (counter = 0; counter < nums_elements; ++counter)
    {
            printf("Inserire valore %d-->", counter+1);
            scanf("%lf", &((*array)[counter]));
    }
    return (nums_elements);
}

要调用,请执行以下操作:

int count;
double *insieme_A;
count = get_array(&insieme_A);

【讨论】:

  • 哇,非常感谢!你解释得非常简单易懂。再次感谢它终于起作用了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 2017-05-25
  • 2020-05-09
相关资源
最近更新 更多