美文网首页
字符串:字符串变量

字符串:字符串变量

作者: 爱生活_更爱挺自己 | 来源:发表于2020-11-02 10:56 被阅读0次

1、字符串常量

​ char* s = “Hello,world”;

#inlcude<stdio.h>

int main(void)
{
    int i=0;
    char *s = "Hello world";
    char *s2 = "Hello world";
    
    printf("&i=%p\n", &i);
    printf("s =%p\n", s);
    printf("s2=%p\n",s2);
    printf("Here!s[0]=%c\n", s[0]);
    
    return 0;
}
&i=0xbff1fd6c
s =0xe1f82
s2=0xe1f82
Here!s[0]=H

【释】s和s2指向相同地方的地址,地址很小,位于程序的代码段而且是只读的,如果试图修改其中的值,操作系统会有保护机制会让程序崩溃掉

  • s是一个指针,初始化为指向一个字符串常量

    • 由于这个常量所在的地方,所以实际上s是const char* s,但是由于历史的原因,编译器接收不带const的写法
    • 但是试图对s所指的字符串做斜土会导致严重的后果
  • 如果需要修改字符串,应该用数组:

    • char s[] = “Hello,world!”;
#inlcude<stdio.h>

int main(void)
{
    int i=0;
    char *s = "Hello world";
    char *s2 = "Hello world";
    char s3[] = "Hello world";
    
    printf("&i=%p\n", &i);
    printf("s =%p\n", s);
    printf("s2=%p\n",s2);
    printf("s3=%p\n", s3);
    s3[0]='B';
    printf("Here!s3[0]=%c\n", s3[0]);
    
    return 0;
}
&i=0xbff03d64
s =0xfdf7c
s2=0xfdf7c
s3=0xbff03d50
Here!s3[0]=B

指针还是数组?

  • char *str = “Hello”;

  • char word[] = “Hello”;

  • 数组:这个字符串在这里

    • 作为本地变量空间自动被回收
  • 指针:这个字符串不知道在哪里

    • 处理参数
    • 动态分配空间
  • 如果要构造一个字符串->数组

  • 如果要处理一个字符串->指针

char *是字符串?

  • 字符串可以表达为char* 的形式

  • char *不一定是字符串

    • 本意是指向字符的指针,可能指向的是字符数组(就像int *一样)
    • 只有它缩回的字符数组有结尾的0,才能说它所指的是字符串

相关文章

网友评论

      本文标题:字符串:字符串变量

      本文链接:https://www.haomeiwen.com/subject/upopvktx.html