← 返回首页
C语言系列教程(二十八)
发表时间:2021-03-29 18:15:55
指向字符串的指针

我们知道字符串的本质就是字符数组,既然是数组那么指针也可以指向字符数组。

1.指向字符串的指针

指向字符串的指针有以下定义方式。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char arr[]="https://www.simoniu.com"; //字符数组
    char* str = arr;
    char* str1="https://www.simoniu.com"; //字符串常量
    char* str2 = str1;

    for(int i=0;i<strlen(arr);i++){
    printf("%c",*str);
    str++;
    }
    printf("\n---------------------\n");

    for(int i=0;;i++){
         if(*str1=='\0'){
             break;
     }
     printf("%c",*str1);
     str1++;
     }
    printf("\n---------------------\n");
    printf("%s\n",str);
    printf("%s\n",str2);
    puts(str2);
    return 0;
}

运行结果:

2.字符指针与字符数组的区别

char *s = “abcd”; 此时"abcd"存放在常量区。通过指针只可以访问字符串常量,而不可以改变它。 而char arr[20] = “abcd”; 此时 "abcd"存放在栈。可以通过指针去访问和修改数组内容。

例如:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char arr[]="https://www.simoniu.com";

    char* str1="https://www.simoniu.com";//str1是字符串常量。 

    arr[0]='H';
    //str1[0]='H'; //错误,因为str1是字符串常量,只能读取不能写入。 
    puts(arr);

    puts(str1);
    //arr="hello,world"; //只能在定义的同时初始化。 
    str1="hello,world!"; //str1指向另一个字符串常量。 
    //str1[0]='H'; //错误。 
    puts(str1);

    str1=arr;
    str1[0]='H';//ok,因为此时str1指向的是字符串变量。 
    puts(str1);
    return 0;
}

运行结果:

Https://www.simoniu.com
https://www.simoniu.com
hello,world!
Https://www.simoniu.com

在编程过程中如果只涉及到对字符串的读取,那么字符数组和字符串常量都能够满足要求;如果有写入(修改)操作,那么只能使用字符数组,不能使用字符串常量。

获取用户输入的字符串就是一个典型的写入操作,只能使用字符数组,不能使用字符串常量,请看下面的代码:

#include <stdio.h>
int main(){
    char str[20];
    gets(str);
    printf("%s\n", str);
    return 0;
}