簡體   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