zoukankan      html  css  js  c++  java
  • 【C】字符串常量和字符数组

    此次博客是转载某位博主的文章,不过现在找不到了,所以先声明一下。

    先贴一段代码:

    #include <stdio.h>
    int main(int argc, const char** argv)
    {
        char str_1[6] = "Crazy1";
        char* str_2 = "Crazy2";
        if (str_1 == "Crazy1") {
            printf("%s
    ", "字符数组OK");
        }
        if (str_2 == "Crazy2") {
            printf("%s
    ", "字符串常量OK");
        }
    
        return 0;
    }
    

    结果: 字符串常量OK

    区别分析:

      字符数组和字符串常量的区别,本质区别:前者在栈上分配空间,后者存储在静态存储区等。

    这里 str_2是指针, 指向”Crazy2″这个字符串常量的内存首地址, 而str_1是在栈里分配的字符数组”Crazy1″的首地址.

    字符串常量是在编译时就确定的, 而字符数组是在运行时确定的.

    字符数组为什么不行呢? 很显然 因为他们不属于同一个内存空间.

    建议: C字符串比较都使用strcmp

    C++ string类就可以直接使用==操作。

    反汇编:

    .section .rodata
    .LC0:
    .string "Crazy2"
    .LC1:
    .string "OK"
    .text
    .globl main
    .type main, @function
    main:
    pushl %ebp
    movl %esp, %ebp
    andl $-16, %esp
    subl $32, %esp
    movl $2053206595, 22(%esp)
    movw $12665, 26(%esp)
    movl $.LC0, 28(%esp)
    cmpl $.LC0, 28(%esp)
    jne .L2
    movl $.LC1, (%esp)
    call puts
    .L2:
    movl $0, %eax
    leave
    ret
    .size main, .-main
    .ident "GCC: (GNU) 4.5.1 20100924 (Red Hat 4.5.1-4)"
    .section .note.GNU-stack,"",@progbits  
  • 相关阅读:
    leetcode-14
    贪心算法
    MySQL索引
    leetcode-13
    leetcode-12
    leetcode-11
    深度和广度优先搜索
    CentOS出错You don't have permission to access on this server
    linux给文件或目录添加apache权限
    让CentOS在同一个窗口打开文件夹
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6946845.html
Copyright © 2011-2022 走看看