0

Code:

#include <iostream>
using namespace std;

int main(int argc, const char * argv[]) {
    char testChar[] = {'a','b','c'};
    char *testPointer = testChar ;
    cout << testPointer << endl;
    return 0;
}

Question:

When I use cout << mypointer,

  1. Why does to print each letter of the array and the mess(refer to output) at the end? My assumption is when I see out the pointer points to the first letter prints then the second then etc and prints the stuff at the end.
  2. What is the mess (refer to output) at the end , the address?

Comments:

  • I know at the end of the array there's suppose to be a null pointer right?
  • I learnt this a year ago and forget please help me recall what is going on.

Output:

abc 310 367 277_ 377   
Program ended with exit code: 0

2 Answers 2

4

When printing out a string (or char array in your case), it must be terminated by a null character \0, otherwise cout will continue to print out characters located in memory past the intended string until it either hits a null character, or it accesses memory it is not allowed to read from which results in a segmentation fault.

That "mess" at the end that is being printed are the values located in the memory locations immediately past the char array.

Sign up to request clarification or add additional context in comments.

2 Comments

Exactly.. if you used printf == printf("%s\n", testPointer); == to print the string out you'd see the exact same results, which shows that it's not related to cout itself but to how the string has been formed.
You might prefer to initialize strings this way: char testChar[] = "abc";. This will automatically add a null-terminator at the end of the string. If you examine the results of cout << sizeof(testChar);, you'll see there are actually 4 bytes of memory allocated: 3 characters plus a null terminator.
0

Also after initializing char testChar[] = "abc"; you actually don't need 'char *testPointer = testChar' statement since testChar is itself an address to the first element of the array. So cout << testChar << endl;will do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.