我的变量存储在 C 中的内存中的哪个位置? [英] Where in memory are my variables stored in C?

查看:24
本文介绍了我的变量存储在 C 中的内存中的哪个位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到内存分为四段:数据、堆、栈、代码,其中做全局变量、静态变量、常量数据类型、局部变量(在函数中定义和声明)、变量(在主函数中))、指针和动态分配的空间(使用 malloc 和 calloc)是否存储在内存中?

By considering that the memory is divided into four segments: data, heap, stack, and code, where do global variables, static variables, constant data types, local variables (defined and declared in functions), variables (in main function), pointers, and dynamically allocated space (using malloc and calloc) get stored in memory?

我认为它们会被分配如下:

I think they would be allocated as follows:

  • 全局变量 -------> 数据
  • 静态变量 -------> 数据
  • 常量数据类型----->代码
  • 局部变量(在函数中声明和定义)-------->堆栈
  • 主函数中声明和定义的变量----->堆
  • 指针(例如,char *arrint *arr)-------> heap
  • 动态分配空间(使用 malloc 和 calloc)--------> 栈
  • Global variables -------> data
  • Static variables -------> data
  • Constant data types -----> code
  • Local variables (declared and defined in functions) --------> stack
  • Variables declared and defined in main function -----> heap
  • Pointers (for example, char *arr, int *arr) -------> heap
  • Dynamically allocated space (using malloc and calloc) --------> stack

我只是从 C 的角度来指代这些变量.

I am referring to these variables only from the C perspective.

如果我是 C 新手,如果我错了,请纠正我.

Please correct me if I am wrong as I am new to C.

推荐答案

你答对了其中一些问题,但写问题的人至少在一个问题上欺骗了你:

You got some of these right, but whoever wrote the questions tricked you on at least one question:

  • 全局变量 -------> 数据(正确)
  • 静态变量 -------> 数据(正确)
  • 常量数据类型 -----> 代码和/或数据.当常量本身存储在数据段中,并且对它的引用将嵌入代码中时,请考虑字符串文字
  • 局部变量(在函数中声明和定义)-------->堆栈(正确)
  • main 函数中声明和定义的变量 -----> heap 也是栈(老师想骗你)
  • pointers(ex: char *arr, int *arr) -------> heap 数据或堆栈,取决于在上下文上.C 允许您声明全局或 static 指针,在这种情况下,指针本身将在数据段中结束.
  • 动态分配空间(使用malloc, calloc, realloc) --------> stack
  • global variables -------> data (correct)
  • static variables -------> data (correct)
  • constant data types -----> code and/or data. Consider string literals for a situation when a constant itself would be stored in the data segment, and references to it would be embedded in the code
  • local variables(declared and defined in functions) --------> stack (correct)
  • variables declared and defined in main function -----> heap also stack (the teacher was trying to trick you)
  • pointers(ex: char *arr, int *arr) -------> heap data or stack, depending on the context. C lets you declare a global or a static pointer, in which case the pointer itself would end up in the data segment.
  • dynamically allocated space(using malloc, calloc, realloc) --------> stack heap

值得一提的是,栈"的正式名称是自动存储类".

It is worth mentioning that "stack" is officially called "automatic storage class".

这篇关于我的变量存储在 C 中的内存中的哪个位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆