Ryan
Ryan

Reputation: 21

How does an index increment work in c++

My tutor told me to use an index to keep track of which character in the line the program is at. How does an index work exactly? I know its similar to count but other than that I am not sure.

Upvotes: 1

Views: 1061

Answers (3)

Michael McGuire
Michael McGuire

Reputation: 1034

In the beginning, it helped me to think of indexes as bookmarks. The bookmark keeps track of the last thing at which I was looking.

However, to really understand indexes, you should investigate pointers. You need to understand how structures are stored in memory, what addresses are, and how to sanely move from one address to another.

Upvotes: 1

peacemaker
peacemaker

Reputation: 2591

By index he just means a pointer to the specific character. This can simply be an integer keeping track of the characters position or an actual pointer type.

string test = "Hello";
const int sLength = 5;
int index = 0;
for ( ; index < sLength ; index++ )
{
    cout << "Character at index " << index << " = " << test[index];
}

Upvotes: 1

zneak
zneak

Reputation: 138051

At a high level, an index works on a collection. It simply says "I want the nth element of that collection" (where n is your index).

So if you have:

int foo[] = {2, 3, 5, 8, 13}; // array of 5 integers

Using 0 as the index will give you 2, using 1 will give you 3, using 2 will give you 5, using 3 will give you 8 and using 4 will give you 13.

All these are constant indices, so they will always give you the same result. However, if you use a variable as an index, that means you can retrieve a varying element from your collection.

In the case of an array, that collection is simply a block of contiguous memory. The array itself is a memory address, and by adding the index to that memory address, you find the element you're looking for.

Upvotes: 1

Related Questions