我正在尝试记录一些代码,以提高我对指针的了解和一般 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
它们声明未初始化。
关于c - 使用 malloc() 函数和指针理解代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32011317/