c - 使用 malloc() 函数和指针理解代码

标签 c memory-management dynamic-allocation

我正在尝试记录一些代码,以提高我对指针的了解和一般 ANSI C 能力。

 ...
 int static_store = 30;
 const char * pcg = "String Literal";
 int main()
 {
     int auto_store = 40;
     char auto_string[] = "Auto char Array";
     int * pi;
     char * pcl;
     pi = (int *) malloc(sizeof(int));
     *pi = 35;
     pcl = (char *) malloc(strlen("Dynamic String") + 1);
     strcpy(pcl, "Dynamic String");
 ...

乍一看,两个指针被初始化,pi 和 pcl,分别为 int 和 char 类型。

但是后面的几行让我感到困惑,我不明白发生了什么。我可以看到正在调用 malloc 来分配 int (40) 大小的内存。是给变量pi和pcl分配内存吗?

最佳答案

Is it assigning memory to the variables pi and pcl?

是的,malloc正在为这些指针分配内存。

pi 分配的内存等于 sizeof(int)(可能会有所不同),pcl 分配的内存等于 字符串长度加 1(空字符加 1)。

From first looks, two pointers are initialised, pi and pcl, of type int and char respectively

它们声明未初始化。

注意-Please don't cast return of malloc

关于c - 使用 malloc() 函数和指针理解代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32011317/

相关文章:

c - 将字典内容写入文件时出现段错误

逐字节比较两个文件

java - 如何在 x64 windows7 上为 tomcat 分配超过 1 GB 的内存

c++ - CUDA cuFFT 架构 x86_64 的 undefined symbol

c++ - 获取交换功能的段错误 11

iphone - 有以下问题可以提交申请吗?

c++ - 在 C++ 中动态加载的库分配的基类指针上调用 delete 的安全性

c - 在c中使用动态分配输入字符串列表

从 c 调用 Lua 脚本中的一个特定函数

c - 为什么我的指针大小在 64 位计算机上是 4 个字节?