当前位置:网站首页>程序员老鸟都会搞错的问题 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);
}
边栏推荐
- There are three iPhone se 2022 models in the Eurasian Economic Commission database
- Correspondence between STM32 model and contex M
- open-mmlab labelImg mmdetection
- 共用体(union)详解【C语言】
- ESP8266使用arduino连接阿里云物联网
- RT thread API reference manual
- List and set
- 电商数据分析--薪资预测(线性回归)
- 优先级反转与死锁
- C language, log print file name, function name, line number, date and time
猜你喜欢

uCOS-III 的特点、任务状态、启动
![C language callback function [C language]](/img/7b/910016123738240e24549ddea8a162.png)
C language callback function [C language]

Togglebutton realizes the effect of switching lights

Machine learning -- linear regression (sklearn)

Reno7 60W super flash charging architecture

Mall project -- day09 -- order module

高通&MTK&麒麟 手機平臺USB3.0方案對比

I2C总线时序详解

Gallery之图片浏览、组件学习

共用体(union)详解【C语言】
随机推荐
Word排版(小計)
MongoDB
Contiki源码+原理+功能+编程+移植+驱动+网络(转)
Connexion sans mot de passe du noeud distribué
【yarn】CDP集群 Yarn配置capacity调度器批量分配
Dead loop in FreeRTOS task function
Comparison of solutions of Qualcomm & MTK & Kirin mobile platform USB3.0
MySQL数据库面试题
Machine learning -- linear regression (sklearn)
uCOS-III 的特点、任务状态、启动
电商数据分析--薪资预测(线性回归)
Pytorch-温度预测
Using LinkedHashMap to realize the caching of an LRU algorithm
[yarn] CDP cluster yarn configuration capacity scheduler batch allocation
arduino获取数组的长度
I2C bus timing explanation
C语言,log打印文件名、函数名、行号、日期时间
C language, log print file name, function name, line number, date and time
Pytorch four commonly used optimizer tests
E-commerce data analysis -- User Behavior Analysis