c - 这是 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);
}
解决方案
malloc() 返回一个 void 指针,因为它需要是通用的,能够为您提供所需的任何类型的指针。这意味着它必须在使用前进行转换。您对 malloc 的使用是正确的, malloc 返回的指针会自动转换为 double* 类型的指针(指向 double 的指针)。
推荐阅读
- django - SQLAchemy 和 Django
- excel - Excel VBA 更新链接
- json - 使字符串同时有效 JSON 和 shell 转义
- tensorflow - 在tensorflow中,如何枚举训练数据(对比pytorch)
- javascript - 如何在 node.js sequelize 中使用 varchar?
- java - Docker&Java:构建不反映新文件
- google-apps-script - 是否可以从谷歌表中隐藏谷歌脚本?
- c# - Polly - 请在调用异步 ExecuteAsync(和类似)方法时使用异步定义的策略
- python - 制作石头剪刀布游戏时的值错误
- php - WordPress 类别搜索简码不显示选项