Debuging Error

This code appears to work, it just causes an error. But I do not understand the message because I am not experienced in this language. This program should take the name in the array and out put that persons initials.

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
#include "stdafx.h"
#include <iostream>
using namespace std;


int main()
{
char name[] = "John Doe";
char initials[2];
int length, i;

for(length = 0;name[length];length++)
{
;
}

initials[0] = name[0];

for(i = 0;i < length;i++)
{
if(name[i] == 32)
{
break;
}
}

initials[1] = name[i + 1];

initials[2] = 0;

cout << initials << endl;

return(0);
}
What does the error say?
Debug Error!

Program: ...ron\Documents\Visual Studio
2008\Projects\initials\Debug\initials.exe
Module: ...ron\Documents\Visual Studio
2008\Projects\initials\Debug\initials.exe
File:

Run-Time Check Failure #2 - Stack around the variable 'initials' was corupted.

(Press Retry to debug the application)
I this in visual studio c++ you must create a new file here and look for win32 console application or the "cpp file". In this statement you can put a pure c++ codes without the #include "stdafx.h"

In my dev c++, it seems to work fine and you nearly forgot to put a cin.get() in line 32 to show what you want to see.. :)

Tell me if this helps. :)

Best regards,
nemesis
1
2
3
4
5
6
7
char initials[2];
//...
initials[0] = name[0];
//...
initials[1] = name[i + 1];

initials[2] = 0; // <- Index over array boundary.  

Topic archived. No new replies allowed.