字符*海峡;海峡=" HELLO英寸;如何没有字符串分配任何内存的工作? [英] char *str; str="HELLO"; How does that work without allocating any memory for the string?

查看:173
本文介绍了字符*海峡;海峡=" HELLO英寸;如何没有字符串分配任何内存的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:


  1. 我怎么可以存储的字符串不为它分配任何内存。 STR 是一个字符指针,指向到char变量 I 。当我添加海峡=你好; 不是我使用 5 从该位置 4 未分配?

  1. How can I store a string without allocating any memory for it. str is a character pointer and is pointing to where char variable i. When I add str = "Hello"; aren't I using 5 bytes from that location 4 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屋!

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