• 字符串常量与字符串数组区别


    在论坛上看到过有人说字符串常量存储在只读区域,不能写只能读;

    而字符数组是栈上,可读可写。

    #include<stdio.h>
    #include<stdarg.h>
    
    int main(){
    
    	/*字符数组存储于动态内存中,可以进行赋值操作*/
    	char message[]={'h','e','l','l',''};
    	message[2]='a';
    	printf("%s
    ",message);
    	
    	/*指向字符数组的指针也可以对内存进行操作*/
    	char *p=message;
    	p[1]='n';
    	printf("%s
    ",p);
    
    	/*常量字符串存储于静态内存中,不能进行赋值操作*/
    	char *p2="abcdef";
    	printf("%s
    ",p2);//可以记性读取
    	//p2[1]='n';//但是不能进行赋值操作
    	printf("%s
    ",p2);
    
    	return 0;
    }
    

    有个猜测,字符串常量只有一个,任意指向它的指针都是共用这一块内存中的数据

    //一个字符串常量只有一块内存区域??
    #include<iostream>
    using namespace std;
    void main(void)
    {
    	if("join"=="join")
    		cout<<"equal
    ";
    	else cout<<"not equal
    "; //equal
    
    	char* str1="good";
    	char* str2="good";
    	if(str1==str2)
    		cout<<"equal
    ";
    	else cout<<"not equal
    ";  //equal
    
    	char buf1[]="hello";
    	char buf2[]="hello";
    	if(buf1==buf2)
    		cout<<"equal
    ";
    	else cout<<"not equal
    ";  //not equal
    	
    }
    

    最后放一段恶心的题目,每次都蒙圈

    //指针与数组及字符串等的关系.cpp  
    
    #include<iostream.h>
    
    char* c[]={"You can make statement","for the topic","The sentences","How about"};
    char* *p[]={c+3,c+2,c+1,c};
    char***pp=p;
    void main(void)
    {
    	
    	cout<<**++pp<<endl;           //(1)The sentences
    
    	cout<< * --* ++pp+3 <<endl;   //(2) can make statements
    
    	cout<<*pp[-2]+3<<endl;       //(3) about
    
    	cout<<pp[-1][-1]+3<<endl;    //(4) the topic
    
    }
    
    
    /*  
    (1) **++pp等价于**(++pp),运算后pp指针指向p[1],而p[1]指针指向c[2],c[2]指向字符串“The sentences”
    (2)++pp后,pp指针指向p[2],--(*(++pp))指向c[0],c[0]指向字符串“You can make statements”.pp还是指向
    原来的p[2].
    (3)pp[-2]等价于*(pp-2),pp[-2]指向c[3].pp还是指向p[2].
    (4)pp[-1]指向c[2],pp[-1][-1]等价于*(pp[-1]-1),pp[-1]-1指向c[1],c[1]指向字符串“for the topic”
    
    */
    

      

  • 相关阅读:
    THUSC2019游记
    2019-8-2-WPF-从文件加载字体
    2019-8-2-WPF-从文件加载字体
    2018-8-10-VisualStudio-合并代码文件
    2018-8-10-VisualStudio-合并代码文件
    2018-8-10-UWP-分享用那个图标
    2018-8-10-UWP-分享用那个图标
    2018-8-10-WPF-可获得焦点属性
    2018-8-10-WPF-可获得焦点属性
    2018-8-10-WPF-好看的矢量图标
  • 原文地址:https://www.cnblogs.com/sjw1357/p/3836062.html
Copyright © 2020-2023  润新知