字符串

  1. 字符串的声明和定义
  • 字符串是以空字符(\0)结尾的char类型数组,如果没有空字符(\0),那么就是字符数组而不是字符串。
  • 利用数组和指针形式创建字符串
#include <stdio.h>
int main() {
	char words_1[30] = "\"Run! Forrest, run!\"";  
        //初始化数组把**静态存储区的字符串**拷贝到**动态存储区的数组**中,**数组名words_1为地址常量**
	const char *words_2 = "Nice to meet you!";   
        //初始化指针把静态存储区字符串的地址拷贝给指针变量words_2,words_2指向该字符串的首字符,但是words_2地址可以改变
	printf("%s\n", words_1);
	printf("%s\n", words_2);
	return 0;
}
  • 如果字符串字面量之间没有间隔,或者用空白字符分隔,C语言会将其视为串联起来的字符串字面量,例如:
#include <stdio.h>
int main() {
	char words[100] = "Hello,"  "nice to meet you!";// Hello与 Nice to meet you!之间虽然有空格,但是输出时连接起来了
	printf("%s", words);
	return 0;
}

  • 如果想输出双引号,需要在双引号前面加上****
#include <stdio.h>
int main() {
	char words[100] = "\"Run! Forrest, run!\"";
	printf("%s", words);
	return 0;
}

  • 字符串储存在静态存储区,程序运行时才会为数组分配内存。
#include <stdio.h>
#define MSG "I'm special"

int main() {
	char string[20] = MSG;//数组形式赋值字符串
	const char* pt = MSG;//指针形式赋值字符串
	printf("%p\n", string); //动态内存里的字符串地址
	printf("%p\n", pt);       //静态存储区里的地址
	printf("%p\n", "I'm special");//静态存储区里的地址
}

posted @ 2021-12-06 20:50  轩邈、  阅读(127)  评论(0编辑  收藏  举报