new_d_array()函数接受一个int类型的参数和double类型的参数。该函数返回一个指针,指向由malloc()函数分配的内存块。int类型的参数指定了动态数组中的元素个数 ,double类型的值用于初始化元素(第一个值赋给第一个元素,以此类推)。编写new_d_array()和show_array()函数的代码完成这个程序

/*下面是使用变参函数的一段程序:

include <stdio.h>

include <string.h>

incude <stdarg.h>

void show_array(const double ar[],int n);
double *new_d_array(int N,...);
int main(void)
{
double p1;
double p2;
p1=new_d_array(5,1.2,2.3,3.4,4.5,5.6);
p2=new_d_array(4,1000.0,20.00,8.08,-1890.0);
show_array(p1,5);
show_array(p2,4);
free(p1);
free(p2);
return 0;
}
new_d_array()函数接受一个int类型的参数和double类型的参数。该函数返回一个指针,指向由malloc()函数分配的内存块。int类型的参数指定了动态数组中的元素个数
,double类型的值用于初始化元素(第一个值赋给第一个元素,以此类推)。编写new_d_array()和show_array()函数的代码完成这个程序
/

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

void show_array(const double ar[], int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("%.2f ", ar[i]);
    }
    printf("\n");
}
double *new_d_array(int N, ...)
{
    double *array = (double *)malloc(N * sizeof(double));
    if (array == NULL)
    {
        fprintf(stderr, "Memory allocation failed\n");
        return NULL;
    }
    va_list args;
    va_start(args, N);
    for (int i = 0; i < N; i++)
    {
        array[i] = va_arg(args, double);
    }
    va_end(args);
    return array; 
}

int main(void)
{
    double *p1;
    double *p2;
    p1 = new_d_array(5, 1.2, 2.3, 3.4, 4.5, 5.6);
    p2 = new_d_array(4, 1000.0, 20.00, 8.08, -1890.0);
    if (p1 != NULL)
    {
        show_array(p1, 5);
        free(p1);
    }
    if (p2 != NULL)
    {
        show_array(p2, 4);
        free(p2); 
    }

    return 0;
}

posted on 2024-08-07 23:21  wessf  阅读(5)  评论(0编辑  收藏  举报