首页 > 解决方案 > 为什么这个正在运行的代码不打印字符串的最后一个值/?

问题描述

我正在使用一个名为 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 (文字字符串中的最后一个字符)

标签: c++stringpointersundefined-behaviorstrlen

解决方案


对于初学者,您忘记为终止零保留内存

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: /

推荐阅读