c - 如果我们改变 char* ptr = ; 指针指向的地址会改变吗?
问题描述
char* ptr = "hello";
ptr = "world";
ptr的地址会变吗?
如果我最初设置ptr = "hello"
,那么我设置ptr = "world"
。去哪儿"hello"
了,它就消失了?
情况1:
[变更前]
ptr = [h][e][l][l][o]; // address of ptr = 10001;
【改动后】
ptr = [w][o][r][l][d]; // address of ptr still = 10001;
或者
案例2:
[变更前]
ptr = [h][e][l][l][o]; // address of ptr = 10001;
【改动后】
ptr = [w][o][r][l][d]; // address of ptr still = 10002;
char* ptr = "hello";
ptr = "world";
// maybe 2 minutes later, i change again
ptr = "something else";
解决方案
指针会改变。文本“hello”保留在内存中,但不再以有效方式访问。
#include <stdio.h>
int main(void)
{
const char* ptr = "hello";
printf("The value of ptr is %p\n", ptr);
ptr = "world";
printf("The value of ptr is %p\n", ptr);
}
The address of ptr is 0000000000404000
The address of ptr is 0000000000404020
推荐阅读
- javascript - 如何在我的 JSON 响应 API 中添加总计(int)字段
- javascript - 在 background.js 中获取标签的元素
- java - addcallback ListenableFuture
- c - 使用makefile编译时如何设置GDB?
- android - 即使变量不匹配,切换语句也会调用 AsyncTask 中的所有案例
- html - 引导分页溢出父 div 取决于分辨率,如何缩小或换行?
- python - ValueError:不支持多类格式
- stripe-payments - 条纹表格未正确显示
- google-cloud-platform - 使用需要 oAuth 的负载均衡器来保护我的后端应用程序
- model - 获取模型的实际数据