繁体   English   中英

这是 malloc() function 的正确用法吗?

[英]Is this proper usage of the malloc() function?

在观看了大量解释 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);
}

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

具体来说,我不明白调用时需要 void 指针。

不需要指针来调用malloc ,它的签名只需要一个 integer ,这是您请求的字节数。

我假设您正在谈论这一行:

rh_ptr = malloc(divisions * sizeof(*rh_ptr));

您可能对sizeof(*rh_ptr)值感到困惑? 因为该表达式计算为rh_ptr的取消引用类型的字节大小,或者在您的情况下计算为double的大小,即 8。

暂无
暂无

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

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