如何指向数组

时间:2018-03-22 23:06:50

标签: c++

作为一个小项目,我试图创建一个简单的程序,使用char数组向后写出一个字符串。

char line[] = "String";
char *endLine = &line[5]

cout << *endline << endl;

这个程序将编译并运行,但我想知道是否有任何方法可以做到这一点,无论数组长度是多少都无关紧要。这样总会编译。我试过了:

char line[] = "String";

char *endLine = &line[sizeof(line)];

cout << *endLine << endl;

但是每次我编译它都不会返回一个字符。

对此有任何帮助将不胜感激。谢谢。

4 个答案:

答案 0 :(得分:4)

请改用std :: string。使用和理解起来要简单得多。

std::string line="String2";
if (!line.empty()){//avoid crashes for empty strings
    std::cout<<line[line.length()-1];
}

在C ++ 11中:

std::string line="String2";
if (!line.empty()){//avoid crashes for empty strings
    std::cout<<line.back();
}

答案 1 :(得分:2)

你想从长度中减去2,因为nul终止符:

char text[] = "Vanilla";
cout << text[sizeof(text) - 2] << "\n";

编辑1:注意:根据评论更正 位置[sizeof(text)]超出界限 位置[sizeof(text) - 1]指的是nul终结符 位置[sizeof(text) - 2]是指最后一个字符,而不是nul。

答案 2 :(得分:0)

Provided you get C strings of arbitrary length (e. g. via some C API: char const* f(void);), you could use strlen:

char const* array = f();
std::cout << array[strlen(array) - 1];

You could assign it to a std::string instead, getting back to Gabriel's answer, but that would create a copy internally, some overhead you might prefer to spare if matter is as easy as in the given case...

This approach would work on the arrays as you provided them, too, however strlen is calculated at runtime whereas Thomas' sizeof approach (and the better alternatives discussed in the comments) is calculated at compile time (i. e. has no impact when running the program).

答案 3 :(得分:0)

试用此代码

 string text="saeed";
for(int i=text.length()-1;i<text.length();i--){
    cout<<text[i];
}