zoukankan      html  css  js  c++  java
  • c语言之创建字符串的两种方式

    在c语言中,一般有两种方式来创建字符串

    //第一种,利用字符指针
    char* p = "hello";
    //第二种:利用字符数组
    char str[] = "hello";

    那么,它们之间有什么区别呢?以例子说明:

    #include<stdio.h>
    #include<iostream>
    char* returnStr()
    {
        char* p = "hello world!";
        return p;
    }
    int main()
    {
        char* str = NULL;
        str = returnStr();
        printf("%s
    ", str);
        system("pause");
        return 0;
    }

    输出:

    以上代码是没有问题的,"hello world"是一个字符串常量,存储在常量区,p指针指向该常量的首字符的地址,当returnStr函数退出时,常量区中仍然存在该常量,因此仍然可以用指针访问到。

    #include<stdio.h>
    #include<iostream>
    char* returnStr()
    {
        char p[] = "hello world!";
        return p;
    }
    int main()
    {
        char* str = NULL;
        str = returnStr();
        printf("%s
    ", str);
        system("pause");
        return 0;
    }

    输出:

    以上代码有问题,输出为乱码。这一段代码和之前的最主要的区别就是returnStr中字符串的定义不同。这里使用字符数组定义字符串。因此这里的字符串并不是一个字符串常量,该字符串为局部变量,存查在栈中,当returnStr函数退出时,该字符串就被释放了,因此再利用指针进行访问时就会访问不到,输出一堆乱码。

    当然 ,如果将char p[] = "hello world!";声明为全局变量,即:

    #include<stdio.h>
    #include<iostream>
    char p[] = "hello world!";
    char* returnStr()
    {
        return p;
    }
    int main()
    {
        char* str = NULL;
        str = returnStr();
        printf("%s
    ", str);
        system("pause");
        return 0;
    }

    那么,该字符串就会存储在全局变量区,一般将全局变量区和静态资源区和常量区视为一个内存空间。因此,同样可以使用指针访问到。

    输出:

  • 相关阅读:
    jquery
    实现元素垂直居中
    浏览器 标准模式和怪异模式
    cookie session ajax
    React props.children
    使用React.lazy报错Import in body of module; reorder to top import/first
    state 和 props 之间的区别
    Harbor打怪升级
    Centos7下安装yum工具
    正则表达式匹配两个特殊字符中间的内容(特殊字符不显示)
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12129140.html
Copyright © 2011-2022 走看看