首页 > 解决方案 > 这是 malloc() 函数的正确用法吗?

问题描述

在观看了大量解释 malloc() 用法的视频后,我无法理解 malloc() 的用法。具体来说,我不明白调用时需要 void 指针。在下面的代码中,我请求一个双精度数组,我在编译时不知道其长度。它按我的预期工作,编译器没有抱怨,但我想知道我是否在更复杂的情况下为自己设置麻烦。这是编译的gcc -Wall -g -o test test.c -lm

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>

int  main()  {

 char in[10];        /*  input from stdin  */
 int index;

 double width;       /*  segment size      */
 int divisions;      /*  number of segments  */
 double start;       /*  lower "Reimann" limit  */
 double end;         /*  upper "Reimann" limit  */
 double *rh_ptr;     /*  base of array of right hand edges */

 printf("Enter start and end values along x axis\n");
 printf("Start -- ");
 fgets(in, 10, stdin);
     sscanf(in, "%lf", &start);
 printf("End   -- ");
 fgets(in, 10, stdin);
     sscanf(in, "%lf", &end);
 printf("Number of divisions for summation -- ");
 fgets(in, 10, stdin);
     sscanf(in, "%i", &divisions);
 width = ((end - start) / (double)divisions);


 rh_ptr = malloc(divisions * sizeof(*rh_ptr));
     if(rh_ptr == NULL) {
        printf("Unable to allocate memory");
        exit(0);
     }

 for(index = 0; index < divisions; index++) {
     rh_ptr[index] = start + (width * (index + 1));
     printf("value = %fl\n", rh_ptr[index]);
 }
     printf("\n\n");

 return(0);
}

标签: c

解决方案


malloc() 返回一个 void 指针,因为它需要是通用的,能够为您提供所需的任何类型的指针。这意味着它必须在使用前进行转换。您对 malloc 的使用是正确的, malloc 返回的指针会自动转换为 double* 类型的指针(指向 double 的指针)。


推荐阅读