c++ - 为什么这个正在运行的代码不打印字符串的最后一个值/?
问题描述
我正在使用一个名为 ncdir 的 PATH(一个外部字符指针)用于其他文件来读取 netcdf 文件。
string temp = "/mnt/BIOPHY-RO/Model_AIFS/AIFS_LFN/";
ncdir = (char*) calloc (temp.length(),sizeof(char));
strcpy (ncdir, temp.c_str());
cout<<"last element of the string: "<<ncdir[sizeof(ncdir)]<<endl;
我希望输出 P 而不是 N (文字字符串中的最后一个字符)
解决方案
对于初学者,您忘记为终止零保留内存
cdir = (char*) calloc (temp.length(),sizeof(char));
其次,表达式sizeof(ncdir)
给出了指针ncdir
的大小而不是指向数组的大小。
考虑到字符串文字的最后一个符号是'/'
bur not 'N'
。
注意:如果它实际上是 C++ 代码,则calloc
使用运算符而不是标准 C 函数new
来分配内存。
这是一个演示程序
#include <iostream>
#include <string>
#include <cstring>
int main()
{
std::string temp = "/mnt/BIOPHY-RO/Model_AIFS/AIFS_LFN/";
char *ncdir = new char[temp.size() + 1];
std::strcpy ( ncdir, temp.c_str() );
std::cout << "last element of the string: " << ncdir[std::strlen( ncdir ) -1] << std::endl;
delete [] ncdir;
}
它的输出是
last element of the string: /
推荐阅读
- struct - Julia:创建具有值约束的 AbstractArray
- javascript - 节点 JS REST Api 使用部分工作的 CORS 限制来源。如何阻止直接请求?
- julia - 在 Julia 中使用 Lsq-Fit
- postgresql - 如何引用一个名为参数的 Camel SQL 组件,其中参数名称是混合大小写并包含空格?
- php - 在脚本中使用“foreach”
- python - 短程序的 Python 循环问题
- java - 拆分字符串行列表并将单词添加到新列表
- git - 是否应该在 git 的 .history 文件夹中跟踪文件
- php - 如何在 Laravel 中显示通知?
- javascript - 在Javascript中按年份过滤对象