c++ - 常量指针 C++ Stroustrup
问题描述
int count_x(const char* p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to nothing)
{
if (p==nullptr)
return 0;
int count = 0;
for (; *p!=0; ++p)
if (*p==x)
++count;
return count;
}
p 是一个指针。const 意味着指针不能被修改。但是在for循环中,有++p,这意味着指针被迭代/递增以访问值*p
那里有一个矛盾 - p 不能被修改,但它正在被递增/修改?
解决方案
C++ 中的声明是从右到左读取的。所以像
const char* p
将阅读:p
是一个非常量指针 a const char
。
显然,p
is not const
,但它指向的是const
。所以*p = 's'
是非法的,但p++
不是。
推荐阅读
- java - Renjin 无法安装(默认)包
- sql-server - SSIS - 如何在 Excel 中获取特定单元格并将其添加到现有表中,因为它是每一行的自己的列
- javascript - 反应 js useState 钩子。单击复选框时如何使用其中的数组更新json对象的状态
- azure - Azure 数据工厂管道上的 SSIS 项目部署,包括 SSH.NET 等第三方库
- python - 在 tkinter 中添加文本时防止调整按钮大小
- rest - 如何通过rest调用或程序设置apache nifi进程属性
- google-app-engine - 谷歌应用引擎错误报告不起作用
- r - R Shiny ggplot2 折线图在使用“key”属性和 facet_grid 时不会显示线条
- vue.js - 仅在满足条件时才使用插槽的后备内容
- python - 无法在 AWS EMR 上下载 nltk 语料库,对已关闭文件进行 I/O 操作