C 语言教程 在线

1519C 结构体

结构体中成员变量分配的空间是按照成员变量中占用空间最大的来作为分配单位,同样成员变量的存储空间也是不能跨分配单位的,如果当前的空间不足,则会存储到下一个分配单位中。

#include <stdio.h>

typedef struct
{
    unsigned char a;
    unsigned int  b;
    unsigned char c;
} debug_size1_t;
typedef struct
{
    unsigned char a;
    unsigned char b;
    unsigned int  c;
} debug_size2_t;

int main(void)
{
    printf("debug_size1_t size=%lu,debug_size2_t size=%lu\r\n", sizeof(debug_size1_t), sizeof(debug_size2_t));
    return 0;
}

编译执行输出结果:

debug_size1_t size=12,debug_size2_t size=8

结构体占用存储空间,以32位机为例

  • 1.debug_size1_t 存储空间分布为a(1byte)+空闲(3byte)+b(4byte)+c(1byte)+空闲(3byte)=12(byte)。
  • 1.debug_size2_t 存储空间分布为a(1byte)+b(1byte)+空闲(2byte)+c(4byte)=8(byte)。

1518C 字符串

'a' 表示是一个字符,"a" 表示一个字符串相当于 'a'+'\0';

'' 里面只能放一个字符;

"" 里面表示是字符串系统自动会在串末尾补一个 0。

1517C 字符串

strlen 与 sizeof的区别:

strlen 是函数,sizeof 是运算操作符,二者得到的结果类型为 size_t,即 unsigned int 类型。

sizeof 计算的是变量的大小,不受字符 \0 影响;

而 strlen 计算的是字符串的长度,以 \0 作为长度判定依据。

更多参考内容:

1516C 字符串

字符串在以如下输入进行初始化的时候需要对 \0 特别注意:

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

如果没有在字符数组最后增加 \0 的话输出结果有误:

// 初始化字符串
char greeting[5] = { 'H', 'e', 'l', 'l', 'o' };
printf("Greeting message: %s\n", greeting);

输出结果:

Greeting message: Hello烫烫烫?侵7(?╔?╚╔╔

在使用不定长数组初始化字符串时默认结尾为 \0

char greeting[] = "Hello";
printf("Greeting message: %s, greeting[] Length: %d\n", greeting, sizeof(greeting));

输出结果:

Greeting message: Hello, greeting[] Length: 6

1515C 字符串

本节涉及函数英文全称

strcmp: string compare 

strcat: string catenate 

strcpy: string copy 

strlen: string length 

strlwr: string lowercase 

strupr: string upercase