字符*海峡;海峡=" HELLO英寸;如何没有字符串分配任何内存的工作? [英] char *str; str="HELLO"; How does that work without allocating any memory for the string?
问题描述
code:
#include <stdio.h>
int main() {
char *str;
char i = 'a';
str = &i;
str = "Hello";
printf("%s, %c, %x, %x", str, i, str, &i);
return 0;
}
我得到这样的输出:
I get this output:
Hello, a, 403064, 28ff0b
我有以下两个疑虑:
I have following two doubts:
-
我怎么可以存储的字符串不为它分配任何内存。
STR
是一个字符指针,指向到char变量I
。当我添加海峡=你好;
不是我使用5
从该位置4
未分配?
How can I store a string without allocating any memory for it.
str
is a character pointer and is pointing to where char variablei
. When I addstr = "Hello";
aren't I using5
bytes from that location4
of which are not allocated?
一直以来,我code 海峡=&放;我;
不应该 STR
和&放大器;我
有相同的值时,我的printf呢?当我删除海峡=你好;
语句 STR
和&放大器;我
相同。如果 STR
和&放大器;我
都是一样的话,我相信,当我说海峡=你好
它应该覆盖'A'
与'H'
,其余 ELLO'\\ 0'
进入后续字节。
Since, I code str = &i;
shouldn't str
and &i
have same value when I printf them? When I remove the str = "Hello";
statement str
and &i
are same. And if str
and &i
are same then I believe when I say str = "Hello"
it should overwrite 'a'
with 'H'
and the rest 'ello\0'
come into the subsequent bytes.
我相信整个问题是与海峡=你好
语句。它似乎并不像我所想的工作。
I believe the whole problem is with str = "Hello"
statement. It doesn't seem to be working like what I think.
请别人解释它是如何工作的?
Please someone explain how it works??
推荐答案
静态的(全局)存储区。你的程序执行前这种分配就完成了。
When the compiler encounters a string literal, in this case "Hello"
, memory is allocated in the static (global) memory area. This "allocation" is done before your program executes.
当您的程序开始执行的主
,堆栈帧被分配给存储的局部变量主要
: STR
和 I
。需要注意的是 STR
是一个简单的变量,只是存储的地址。它不会存储任何字符。它只是存储一个指针。
When your program starts executing at main
, a stack frame is allocated to store the local variables of main
: str
and i
. Note that str
is a simple variable that just stores an address. It does not store any characters. It just stores a pointer.
语句海峡=&放;我;
写入变量 STR
地址我
。
语句海峡=你好
写入变量 STR
,是字符串的地址文字你好
这一直是$由编译器p $ p分配即可。这比的 I
一个完全不同的地址。该分配不动的任何字符单词你好的任何地方都没有。
The statement str = "Hello"
writes into the variable str
, the address of the string literal "Hello"
which has been pre-allocated by the compiler. This is a completely different address than that of i
. That assignment does not move any of the characters in the word "Hello" anywhere at all.
TL; DR在C字符串变量的值只是一个指针。分配给一个字符串变量分配一个号码,即一个地址。
TL;DR the value of a "string" variable in C is just a pointer. Assigning to a string variable is assigning a number, namely an address.
这篇关于字符*海峡;海峡=&QUOT; HELLO英寸;如何没有字符串分配任何内存的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!