Char Array VS Char * [英] Char Array VS Char *

查看:123
本文介绍了Char Array VS Char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个基于问题答案的问题:

This is a question based on answers from question:

const char myVar *与const char myVar []

const char* x = "Hello World!";
const char  x[] = "Hello World!";

我明白现在的区别,但我的新问题是:

I understand the difference now, but my new questions are:

(1)如果我重新赋值x,第一行中的Hello World字符串会发生什么?没有什么会指向它的那一点 - 当范围结束时它会被销毁?

(1) What happens to the "Hello World" string in the first line if I reassign x? Nothing will be pointing to it by that point - would it be destroyed when the scope ended?

(2)除了常量,两个示例由编译器不同地存储在内存中?

(2) Aside from the const-ness, how are the values in the two examples differently stored in memory by the compiler?

推荐答案

放置Hello World! c $ c>会导致编译器在编译的可执行文件中包含该字符串。当程序被执行时,在调用 main 之前在内存中创建该字符串,我相信,即使在汇编调用 __ start (这是静态初始化器开始运行时)。 char * x 的内容未使用 new malloc ,或在 main 的堆栈框架中,因此不能未分配。

Placing "Hello World!" in your code causes the compiler to include that string in the compiled executable. When the program is executed that string is created in memory before the call to main and, I believe, even before the assembly call to __start (which is when static initializers begin running). The contents of char * x are not allocated using new or malloc, or in the stack frame of main, and therefore cannot be unallocated.

在函数或方法中声明的c $ c> char x [20] =Hello World c>在堆栈中分配,而在范围内,实际上会有两个副本Hello World在内存中 - 一个预先加载了可执行文件,一个在堆栈分配的缓冲区中。

However, a char x[20] = "Hello World" declared within a function or method is allocated on the stack, and while in scope, there will actually be two copies of that "Hello World" in memory - one pre-loaded with the executable, one in the stack-allocated buffer.

这篇关于Char Array VS Char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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