当前位置:网站首页>程序员老鸟都会搞错的问题 C语言基础 指针和数组
程序员老鸟都会搞错的问题 C语言基础 指针和数组
2022-07-06 09:17:00 【csdndulala】
// a.c
char name[] = "tom";
// b.c
extern char *name;
void main()
{
printf("%s", name);
}
执行会失败,为什么?
背景知识0
可执行文件包含4类段内容:
.text 存放代码段
.data 存放数据段。已初始化的全局变量或静态变量
.rodata 存放只读数据段。如字符串常量
.bss 存放未初始化的全局或静态变量。背景知识1
char a[] = “abc”;
char *b = “def”;
a和b有什么区别?分别放在哪个段内?
区别1:b是一个变量,有自己的地址以及存储的数据;a只是一个名字,a就是“abc”的地址。(可以打印a和&a,是一样的)
区别2:“abc”存储在data段,“def”存储在rodata段
区别3:“abc”内容可以修改,“def”内容不能修改背景知识2
char a[] = “abc”;
char *b = a;
问:a[0]和b[0] 有什么区别?
a[0]直接取值;b[0]先找到b存储的值(a地址),然后根据a地址取值
地址随便取的 a的值是0x3315,a[0]的地址也是0x3315
// a.c
char name[] = "tom";
// b.c
extern char *name;
void main()
{
printf("%s", name);
}
因此在b.c中:extern char *name; 声明name是一个指针,因此在打印name的时候,会先找到name存储的内容:“tom”,然后将“tom”作为地址去取值。
解决方法1:
// a.c
char name[] = "tom";
// b.c
extern char name[];
void main()
{
printf("%s", name);
}
解决方法2:
// a.c
char *name = "tom";
// b.c
extern char *name;
void main()
{
printf("%s", name);
}
边栏推荐
猜你喜欢

Apprentissage automatique - - régression linéaire (sklearn)

MongoDB

MP3mini播放模块arduino<DFRobotDFPlayerMini.h>函数详解

RT-Thread的main线程“卡死”的一种可能原因及解决方案

mysql实现读写分离

FTP文件上传文件实现,定时扫描文件夹上传指定格式文件文件到服务器,C语言实现FTP文件上传详解及代码案例实现

arduino JSON数据信息解析

Come and walk into the JVM

MongoDB

Characteristics, task status and startup of UCOS III
随机推荐
STM32 如何定位导致发生 hard fault 的代码段
[mrctf2020] dolls
Some concepts often asked in database interview
Basic knowledge of lithium battery
Mysql database interview questions
SQL time injection
MySQL主从复制的原理以及实现
open-mmlab labelImg mmdetection
arduino获取随机数
Selective sorting and bubble sorting [C language]
Inline detailed explanation [C language]
[BSidesCF_2020]Had_ a_ bad_ day
[template] KMP string matching
【yarn】Yarn container 日志清理
Correspondence between STM32 model and contex M
[Kerberos] deeply understand the Kerberos ticket life cycle
Implementation scheme of distributed transaction
Détails du Protocole Internet
荣耀Magic 3Pro 充电架构分析
Oppo vooc fast charging circuit and protocol