C语言 字符串指针和字符串数组使用区别

字符串指针和字符串数组使用区别

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <stdlib.h>
 4 
 5 int main(void)
 6 {
 7     char str1[]="this is str1!";  
 8     puts(str1);
 9     
10     strcpy(str1,"new str1");
11     puts(str1);
12     
13     char *subStr=str1+2;  // 指针指向str1+2的位置,即输出:w str1
14     puts(subStr);
15 
16     /* 错误用法
17     str1 = "F1";  str1是常量不能出现在=左边
18     puts(str1);
19     */
20 
21 
22     char *str2 = "this is str2!";
23     puts(str2);
24 
25     str2 = "new str!"; // 指针直接重新指向新的字符串
26     puts(str2);
27 
28     /* 错误用法
29     strcpy(str2,"F2"); // str2指针指向常量字符串"this is str2!" 不能被修改
30     puts(str2);
31     */
32     exit(0);
33 }

结果如下:

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
原文地址:https://www.cnblogs.com/mmtinfo/p/13752471.html