c - 将 malloc 与静态指针一起使用

标签 c pointers static initialization malloc

我知道声明一个 ststic 变量并以这种方式初始化它static int *st_ptr = malloc(sizeof(int)); 将生成编译错误消息(类型初始值设定项元素不是常量) ,并通过使用单独的语句来解决这个问题 static int *st_ptr; st_ptr = malloc(5*sizeof(int));

<小时/>

我需要了解这种情况下初始化运算符和赋值运算符之间的区别?以及为什么这种方式可以解决问题?

最佳答案

首先,让我们简单介绍一下初始化赋值

  • 初始化:

这用于指定对象的初始值。通常,这意味着仅在定义变量时才会进行初始化。用于初始化对象的称为初始化器。来自 C11 ,章节 6.7.9

An initializer specifies the initial value stored in an object.

  • 作业:

赋值是在任何(有效)给定的执行时间点分配(或设置)变量的值。引用标准,章节6.5.16

An assignment operator stores a value in the object designated by the left operand.

如果是简单赋值(= 运算符),

In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.

<小时/>

也就是说,我认为您的查询与 static 对象的初始化有关。

对于第一种情况,

static int *st_ptr = malloc(sizeof(int)); 

引自C11标准文档,章节§6.7.9,初始化,第4段,

All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.

关于常量表达式,来自同一文档的第6.6章,(强调我的)

Constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators, except when they are contained within a subexpression that is not evaluated.

显然,malloc(sizeof(int)); 不是一个常量表达式,因此我们不能使用它来初始化static对象。

对于第二种情况,

static int *st_ptr;
st_ptr = malloc(5*sizeof(int));

您没有初始化静态对象。您将其保留为未初始化。下一条指令,您将 malloc() 的返回值分配给它。所以你的编译器不会产生任何提示。

关于c - 将 malloc 与静态指针一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29388217/

相关文章:

c++ - 通过 curl 通过 http 发送和接收字符串

c - 在 c 中使用 cmake 和宏自动包含头文件?

c++ - 将指针插入 C++ vector 并进行清理

C# 巨大的 2-dim 数组

php - 动态调用非静态方法

c - 如何在汇编代码中使用c变量

c - Listen() 的队列大小如何工作?

c++ - "no match for operator->* in pos ->* op"

java - 如何将字符串分配给带有错误消息 "Non Static method reference Static Context"的数组列表?

java - 为什么外部类在 java 中不是静态的?