a.out issue

Hello everyone,

New to C++, I have a program that i created and every time I run my a.out it produces my answer, but put a "?" at the end of my output.

What am I doing wrong???

#include<iostream>

using namespace std;

int main()
{
char myWords[4] = {'a','b','y','z'};
cout << myWords << endl;
return 0;
}

a.out = abyz?
Last edited on
closed account (DSLq5Di1)
What you have there is not a c-string, but an array of characters.
http://en.wikipedia.org/wiki/Null-terminated_string

You could output the characters individually cout << myWords[0] << myWords[1] << etc, append a null character to the end char myWords[5] = { ... , '\0' };, or initialize the array with a string literal (implicit null) char myWords[] = "abyz";.
Well when I ran your code, it just output "abyz" with no "?", so I'm guessing it's related to your compiler.
That's the part I don't get, because a friend at school typed the same exact thing and it didn't give him the "?".

I understand what sloppy is saying, but I would like to know why it works this way with some and not with others.
When you output myWords it will print all characters until it finds a null character '\0'. You don't have a null character in the array so it will continue read outside the array. This memory might belong to other variables and such things, depending on what the compiler puts there.
closed account (DSLq5Di1)
You'll see whatever resides in memory after your array of characters, this may be nothing, or it may be something, cout will continue printing characters until a null terminator is encountered.

For an example,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

struct example
{
        static char hello[];
        static char garbage[];
};
// I'm using a struct to ensure hello and garbage are
// contiguous in memory (assuming there is no padding).

char example::hello[] = { 'H', 'e', 'l', 'l', 'o' }; // array of characters
char example::garbage[] = "????"; // null terminated string

int main()
{
        cout << example::hello;
        return 0;
}
Hello????
Thanks you sloppy, makes sense.

Appreciate all the feed back.
Topic archived. No new replies allowed.