Sel*_*rge 3 c printf stdio dynamic-memory-allocation
我有一个用 C 编写的函数,它由一个像这样的指针变量组成
#include<stdio.h>
void print()
{
char *hello="hello world";
fprintf(stdout,"%s",hello);
}
void main()
{
print();
print();
}
Run Code Online (Sandbox Code Playgroud)
如果我调用 print() 函数两次,它会为hello变量分配内存两次吗?
如果我调用 print() 函数两次,它会为 hello 变量分配内存两次吗?
不,它是一个字符串文字并且只分配了一次。
您可以通过检查地址来检查:
fprintf(stdout,"%p: %s\n", hello, hello);
Run Code Online (Sandbox Code Playgroud)
示例输出:
0x563b972277c4: hello world
0x563b972277c4: hello world
Run Code Online (Sandbox Code Playgroud)