char array and pointer

Pages: 123
The name of an array by itself is a pointer to the first element of the array. Passing an array into a function the array decays to a pointer pointing to the first element of the array.

Normally when passing an array into a function the array's size needs to be passed as well. Not needed with C strings since the array is null terminated ('\0').

for loops work with pointers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <cstring>

void forward_print(char[]);
void reverse_print(char[]);

int main()
{
   char cstr[] { "This is a test" };

   forward_print(cstr);

   reverse_print(cstr);
}

void forward_print(char cstr[])
{
   // get the C string's length
   size_t len   { strlen(cstr) };

   // create a pointer to the beginning of the C string
   char*  begin { cstr };

   // create a pointer to one address past the last valid character of the C string
   // the address of the null terminator '\0'
   char*  end   { cstr + len };

   // create a for loop using pointer math
   for (char* itr { begin }; itr != end; itr++)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';
}

void reverse_print(char cstr[])
{
   // get the C string's length
   size_t len     { strlen(cstr) };

   // create a pointer to the last valid character in the C string
   char*  rbegin  { cstr + len - 1 };

   // create a pointer to the address one element before the first valid character
   char*  rend    { cstr - 1 };

   // for loop using pointer math
   for (char* itr { rbegin }; itr != rend; itr--)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';
}

C arrays and pointers/pointer math is a simple form of what C++ calls iterators.

Remember that word, iterator. When you want to loop through the elements of a C++ container, you should use iterators.
I'm still working on that reverse function. If I can eventually be efficient with coding, I would love to pay it forward and help people. I'm going to keep at it. I really put in a lot of time into it and I hope it all pays off.
> How do I use '\0' in order to accomplish this
that's a weird question, ¿why do you think that you need to use '\0'?

> for(int = 0; i < 256; i++)//stuck here but you see what I mean
dutch showed you the exact piece of code that you needed, ¿why did you ignore it?

> I guess I don't know what question to ask.
work on that

> I have cout in both loops. When I build and run it will just print out the reverse function.
don't describe your code, just post it
My teacher said to try and use '/0'. Thats all I got. lol

here is what I have so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using namespace std;
//Function Prototypes
void getText(char words[]);
void printOriginal(char words[]);
void printReverse(char words[]);




int main()
{
   /**************************************************************************************
   *This is such a fun class. I really enjoy learning all there is to know about
   *C++. Array stores this text. The program must print text in original, reverse,
   *backwards order as well as count the letters in each word. The program must
   *be able to: count the number of words, longest word length, and shortest word length
   ***************************************************************************************/

    char words[256];//Array to hold text
    getText(words);//Calls the function to store data into the array.
    printOriginal(words);
    printReverse(words);




    return 0;
}
//function definitions
//Function definition to have the user type text and store it into the array.
void getText(char words[])
{

    cin.getline(words, 256);//saves the data entered by the user.

    }
/***************************************************************************************/
//Function displays what the user is prompt to enter.
void printOriginal(char words[])
{
    char *wordsptr = words;
    cout<<"Original Order"<<endl;
 for(int i = 0; i < strlen(words); i++)
 {
     cout<<words[i];
 }

 cout<<endl;
}
/***************************************************************************************************************/
void printReverse(char words[])//Function displays text in reverse.
{
    char *wordsptr = words;

    cout<<"Reverse Order"<<endl;

    for(int i = strlen(words)-1; i >= strlen(words); i--)
    {

        cout<<words[i]<<endl;
    }

    cout<<endl;

}
/**********************************************************************************************************************/


for(int i = strlen(words)-1; i >= strlen(words); i--)
Still pretty much the same issue here as before.
Ask yourself this: When should the loop from line 57 to line 60 stop looping?

Try to go through the code yourself, instruction by instruction.
Let's say words = "hello".

What is strlen("hello")? 5.
So you have
1
2
3
4
for (int i = 4; i >= 5; i--)
{
    cout << words[i] << endl;
}

So first i = 4.
Then, it checks if 4 >= 5. It's not.
This will never loop, because i is never >= 5.

What values does i need to be in order to print every character?
Last edited on
Oh, so are you saying I need to flip it "<"?
You tell me.

Just focus on this: If the input word is "hello", then what values does i need to be, in order, to print the letters reversed.
What should the first value of i be.
What should the last value of i be.
I'm sorry @Ganado that I don't get it right away. If i > 5, which is false. If i < 5, which is true it would loop again. At least thats how I see it.
To print "Hello" in its original order you use (array elements 0 to 4):
1
2
3
4
5
for (size_t i { }; i < 5; i++)
{
   std::cout << word[i] << ' ';
}
std::cout << '\n';


Now you want to print it in reverse order. Array elements 4 to 0.

What is the starting condition for the loop? What is the ending condition?
i-- is that what you mean @Furry Guy?
No, that is the iteration statement.

A for loop consists of

for (initialization statement; ending condition; iteration statement)
1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main()
{
   for (int i { 4 }; i >= 0; i--)
   {
      std::cout << i << ' ';
   }
   std::cout << '\n';
}

What is the output of this for loop?

How might this be used to iterate through a C string of length 5 in reverse order?
Ah, ok. sorry. Oh, if our initial statement is i = 4, then I would say then 0. i < 0.
I'm going check now. Thank you.
In a reverse for loop accessing array elements you want to continue looping when the indexing variable (i) is Greater Than Or Equal to zero.

Checking against Less Than Zero and the loop ends even before it does anything.
ok thanks, I understand that part. Oh do you mind if I fix the loop and then repost my code? Is there a way I can post the output too?
oh you know what. I have to fix the initialize statement then?



1
2
3

for(int i = strlen(words)-1; i >= 0; i--)
That's a C string reverse for loop I like to see!

Posting code and output is easy.

code (using the <> button for the opening/closing code tags):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
   // forward iteration
   for (int i = 0; i <= 4; i++)
   {
      std::cout << i << ' ';
   }
   std::cout << '\n';

   // reverse iteration
   for (int i = 4; i >= 0; i--)
   {
      std::cout << i << ' ';
   }
   std::cout << '\n';
}

Output (using the button to the right of the <> button):
0 1 2 3 4
4 3 2 1 0


About the types of tags that can be used:
http://www.cplusplus.com/articles/z13hAqkS/
Last edited on
A better reverse-for-loop idiom is the following. It even works for an unsigned index.

 
for (size_t i = strlen(words); i-- > 0; )

Last edited on
oh wow, that's cool. for some reason my program didn't post. let me try again.
Pages: 123