关于字符串指针

来源:互联网 发布:模锻力计算模拟软件 编辑:程序博客网 时间:2024/06/05 18:57

1、

#include <stdio.h>int main(){char *p = "1edr";printf("p = %s\n",p);if(*p == '1')   printf("*p = '1'\n");return 1;}

运行结果:

p = 1edr

*p = '1'


指针的本质就是一个存储地址的变量,它存储的一定是地址, char *p = "1edr"实际上就是把字符串‘1’这个首字符的地址赋给指针p。而printf中的%s也指定了printf第二个参数必须是地址,printf会输出地址上的值。

所以

#include <stdio.h>int main(){char *p = '1';if(*p == '1')   printf("*p = '1'\n");return 1;}

运行结果:

segment fault

因为char *p = '1';并不是将字符'1'的地址赋给了p,而是将'1'强制转换成了一个地址,然后赋值给了p,这样因为地址‘1’是不允许访问的,所以*p就会导致地址非法访问。


2、

C/C++code?
1
2
3
4
5
char *m "hello";
    *(m+1) 's';
    for(;*m != '\0';m++){
        printf("%c\n",*m);
    }

但是出运行时错误。
----------------------------------------------------------
用数组下标的方式是可以修改的:
C/C++code?
1
2
3
4
5
6
7
8
int 0;
    char w[] "hello";
    w[1] 's';
     
    while(w[i] != '\0'){
        printf("%c\n",w[i]);
        i++;
    }
char *m "hello";<=>const char*m="hello";
char *m "hello";
"hello"保存在静态数据区,该数据不能修改.
由指针m指向. 不能通过指针m来修改静态数据区的值.

char *p = "hello";本质是把常量区存放"hello"这六个字符的地址赋给了指针p,常量区地址上的内容是不允许被修改的,所以无法通过指针修改这个字符串。

如果想要修改字符串有两个方法,一是可以用数组来存储字符串,这样字符串就存储在栈区,二是可以用malloc,这样字符串就存储在堆区。pa = (char*)malloc(5 * sizeof(char));

0 0
原创粉丝点击