usage of char array which elements are mutilple STRINGs ended with a "\0"

本文详细解读了C语言中字符数组的使用方式,特别是关于字符串常量的理解,包括字符串结尾的符号的作用,以及如何正确引用和打印数组中的多个字符串。通过实例代码和执行结果的分析,帮助读者深入理解C语言的基本语法特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

usage of char array which elements are mutilple STRINGs ended with a "\0".

#include <stdio.h>


char stringsarray[] = {
        "many" "strings" "\0"
        "are" "stored" "\0"
        "in a strings_array" "\0"
};


void main(void)
{
        //char *ptr = stringsarray;
        printf("the first element is: %s\n", &stringsarray[0]);
        printf("the second element is: %s\n", &stringsarray[1]);
        printf("the third element is: %s\n", &stringsarray[2]);
        printf("the fourth element is: %s\n", &stringsarray[3]);
        printf("the fifth element is: %s\n", &stringsarray[4]);
//      printf("the sixth element is: %s\n", &stringsarray[5]);
//      printf("the seventh element is: %s\n", &stringsarray[6]);
//      printf("the eighth element is: %s\n", &stringsarray[7]);
}

execution result(compiling with gcc):

book@book-desktop:~/s3c2440/clanguage/strings$ gcc -o exe strings.c
book@book-desktop:~/s3c2440/clanguage/strings$ ./exe
the first element is: manystrings
the second element is: anystrings
the third element is: nystrings
the fourth element is: ystrings
the fifth element is: strings
conclusions:

1. statement "printf("the first element is: %s\n", &stringsarray[0]);", it will print continuously string"strings" until arriving "\0" when finishing printing the first string("many") in STRING0("many" "strings" "\0"). (every strings(constant) are appended with a '\0' as a end symbol by system, thinking in this way, the result of this statement should be "many" only, the part after "many" at the line not include.)

2. there is doubt how to refer to the second line as a part like refering to the first line in a simple way?(please proficients leave direction, thanks!)

there is a such construction in u-boot:

static uchar default_environment[] = {
#if defined(CONFIG_BOOTARGS)
	"bootargs=" CONFIG_BOOTARGS "\0"
#endif
#if defined(CONFIG_BOOTCOMMAND)
	"bootcmd=" CONFIG_BOOTCOMMAND "\0"
#endif
#if defined(CONFIG_RAMBOOTCOMMAND)
	"ramboot=" CONFIG_RAMBOOTCOMMAND "\0"
#endif
#if defined(CONFIG_NFSBOOTCOMMAND)
	"nfsboot=" CONFIG_NFSBOOTCOMMAND "\0"
#endif
#if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
	"bootdelay=" MK_STR (CONFIG_BOOTDELAY) "\0"
#endif
.............................................
};

来自百度知道:

c语言中 unsigned char default_environment[] = { "baudrate=" "115200" "\0"}; 这怎么解释?

C提供了一种字符数组初始化功能,即如果将要对字符数组初始化为几个字符串常量连接起来的时候,可以在右值的{}中直接按顺序写上这几个字符串常量,编译器会把它们自动衔接起来。字符串常量间可以用空格隔开,也可不用隔开。














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值