小编Fis*_*her的帖子

C - 返回没有malloc的char指针

请考虑以下代码:

char* pointerTesting(void) {

    char* test = "hello";
    return test;
}

int main() {

   char* string = pointerTesting();
   printf("string: %s\n", string);
}
Run Code Online (Sandbox Code Playgroud)

编译和运行没有问题.但是,根据我的理解,这应该不起作用,因为分配给test指针的内存在堆栈上,并且在返回main时它被销毁.

所以问题是,如果在pointerTesting()函数中没有malloc,它如何工作?

c heap stack pointers

7
推荐指数
2
解决办法
5340
查看次数

C变量分配时间和空间

如果我有一个带有以下内容的test.c文件

#include ...
int global = 0;

 int main() {
 int local1 = 0;

  while(1) {
  int local2 = 0;
  // Do some operation with one of them
 }
 return 0;
}
Run Code Online (Sandbox Code Playgroud)

所以,如果我必须在while循环中使用其中一个变量,哪一个更受欢迎?

也许我在这里有点模糊,但我想知道时间/空间分配的差异是否真正相关.

c variables heap stack allocation

3
推荐指数
1
解决办法
204
查看次数

标签 统计

c ×2

heap ×2

stack ×2

allocation ×1

pointers ×1

variables ×1