External Errors?

I have some problem with this code, when I try to run it, it says that there are external errors. I'm relatively new to c++.

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
  #include <iostream>
#include <string>
#include <windows.h>
#include <WinBase.h>
#include <stdio.h>
using namespace std;
int i = 0;
int size;
char ToKey[];
bool Spam = false;
string Chars;
int a;


void Sendkey(char Key1) {
	keybd_event(VkKeyScan(Key1),0x9d,0,0);
	keybd_event(VkKeyScan(Key1),0x9d,KEYEVENTF_KEYUP,0);

}
int main() {
	auto size = sizeof(*ToKey)/sizeof(ToKey[0]);
	cout << "Enter Text." <<endl;
	cin >> ToKey;
	cout << "Put in  the word 'start' to activate it!";
	cin >> Chars;
	while(true) {

		if (Chars=="start") {
			if (Spam == false) {
			Spam = true;
			}
			else{
			Spam = false;}}
		if (Spam) {Sendkey(ToKey[i]);}
		if (i==size) 
		{
			Sleep(10);}
	i++;}
	cin.get();
	return 0;
}
In general, when you have a concise repro like this and you are getting a weird error that you don't understand, comment everything out and start bringing it back and recompiling in small chunks. This will help you identify the line causing the problem. In your case, the error comes back when I uncomment line 23:

 
cin >> ToKey;


Taking a look at the definition of ToKey, the problem becomes apparent:

 
char ToKey[];


You have declared a statically sized character array, but it has no length. When you declare a statically sized array, you're telling the compiler "I want to allocate n bytes on the stack in this scope." Because there is no length in your declared array, you're telling it "I want to allocate 0 bytes on the stack in this scope"... which is effectively the same as telling it "I want to do nothing." As a result, the compiler optimizes that instruction as "do nothing", and the symbol "ToKey" does not exist.

You can fix this problem by specifying a length for the character array when you declare it... though this logic is pretty messy and will be prone to crashing. You should rewrite it using std::string instead of loose character arrays.

Now I get the error: Unhandled exception at 0x01031aba in Code.exe: 0xC0000005: Access violation reading location 0x01046000. I fixed the problem and allocated 6K bytes to the char array.
Topic archived. No new replies allowed.