C语言宝典(持续更新)
1、基本知识和概念
指针变量操作
正确操作:
- 赋值
- 解引用
- 取址
- 指针与整数相加减
- 指针递增和递减
- 指针求差:相减的两个指针指向同一数组的不同元素,差值单位与数组类型的单位相同
- 比较
- void *类型在gcc编译等同于char *
错误操作:编译时报错
- 数组名做运算
- 指针变量相加
- 指针变量相乘
const的用法
- 指向const的指针能被const数据和非const数据的地址赋值
double rate[] = {1.12, 1.22};
const double locked[] = {2.45, 55.3};
const double *pc = rate; /*可以*/
pc = locked; /*可以*/- 普通指针只能被非const数据的地址赋值(编译时报错)
const double locked[] = {2.45, 55.3};
double *pc = locked; /*不可以*/字符串字面量
- 字符串字面量之间没有间隔或者空白分割,则视为串联;
- 双引号括起来的内容被视为指向该字符串储存位置的指针;
- 字符串字面量属于静态存储类别(static storage class),表示该字符串只会被存储一次,在整个程序的生命周期内存在;
- 相同的字符串在内存中只有一份;格式化输入输出相同的字符串也只有一份;(与编译器相关);
/*
* 1、STR1、STR2、str5都指向了同一个字符串地址;
* 2、str3数组有自己单独的地址空间;* 3、str4数组在运行时为其分配空间并赋值,是静态存储区字符串的副本;
* 4、格式化输入输出相同的字符串也只有一份;
*/
#include <stdio.h>
#define STR1 "I am a student."
#define STR2 "I am a student."
char str3[] = "I am a student.";
int main(void)
{
char str4[] = "I am a student.";
const char *str5 = "I am a student.";
printf("%p\n", STR1);
printf("%p\n", STR2);
printf("%p\n", str3);
printf("%p\n", str4);
printf("%p\n", str5);
printf("the string size is:%u\n", sizeof(STR1));
printf("the string size is:%u\n", sizeof(STR2));
printf("the string size is:%d\n", sizeof(STR1));
return 0;
}输出结果:0x1055c0x1055c0x210280x7eaeb1b40x1055cthe string size is:16the string size is:16the string size is:16/* 部分数据段汇编代码 */
str3:
.ascii "I am a student.\000"
.section .rodata
.align 2
.LC0:
.ascii "I am a student.\000"
.align 2
.LC1:
.ascii "%p\012\000"
.align 2
.LC2:
.ascii "the string size is:%u\012\000"
.align 2
.LC3:
.ascii "the string size is:%d\012\000" 相关推荐
penkgao 2020-06-25
fengjing81 2020-06-24
拉斯厄尔高福 2020-11-04
嵌入式资讯精选 2020-10-15
zhaochen00 2020-10-13
penkgao 2020-10-13
wanshiyingg 2020-09-29
Mars的自语 2020-09-27
shenwenjie 2020-09-24
一个逗逗 2020-09-22
flycony 2020-09-13
zhaochen00 2020-08-20
Biao 2020-08-20
qingsongzdq 2020-08-19
penkgao 2020-08-17