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

在大多数现代C编译器(如GCC、Clang等)和操作系统(如Linux)中,字符串常量通常被存储在.rodata(Read-Only Data)段中。.rodata段是程序的只读数据段,专门用于存放程序中定义的只读数据,包括字符串常量、全局常量等。

.rodata不等同于.data段,位置在text和data段之间,靠近text段:   text---.rodata---.data---.bss

posted on 2021-12-06 20:50  轩~邈  阅读(145)  评论(0)    收藏  举报