John Tedesco
John Tedesco

Reputation: 55

How to point to the last item in an array

As a small project I am trying to make a simple program that will write out a string backwards using a char array.

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

cout << *endline << endl;

This program will compile and run but I am wondering if there is any way to do it so that it does not matter what the arrays length is. Such that is will always compile. I have tried:

char line[] = "String";

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

cout << *endLine << endl;

However every time I have compiled this it would not return a character.

Any help on this would be appreciated. Thank you.

Upvotes: 0

Views: 382

Answers (4)

Saeed Muhammed
Saeed Muhammed

Reputation: 9

Try This Code

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

Upvotes: 0

Aconcagua
Aconcagua

Reputation: 25518

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).

Upvotes: 0

Thomas Matthews
Thomas Matthews

Reputation: 57678

You want to subtract 2 from the length, because of the nul terminator character:

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

Edit 1: Note: corrected per comments.
Location [sizeof(text)] is out of bounds.
Location [sizeof(text) - 1] refers to the nul terminator.
Location [sizeof(text) - 2] refers to the last character, not nul.

Upvotes: 2

Gabriel
Gabriel

Reputation: 3584

Use std::string instead. That's much simpler to use and understand.

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

In C++11:

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

Upvotes: 4

Related Questions