Variable X is being used without being initialized

This is been frustrating me every-time I try and learn more Cplusplus. So I'm hoping this site will be able to help me.

Apparently check needs to be initialized before being used but I just don't see the problem with this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
DWORD SELECT_ELEMENT() {

	char* elements[] = { "fire", "water", "air", "earth" };
	char** e=elements;
	int SelectedElement = '\0';
	char*check;

	cout << "Which element do you want control of?" <<endl;
    cin>>check;

	for(int i=0; i<4; i++)
	{
		if(strcmp(e[i], check)==0) {
			cout << "Match found.";
			 SelectedElement = i;
			break;
		}
	}
	if(SelectedElement=='\0') { 
		cout << "No match found."<<endl;
	} else {
		return SelectedElement;
	}
}
This
cin >> check;
takes input from the keyboard and writes it to the memory that the pointer named check is pointing at. What memory is it pointing at? Let's take a look...

char* check;
Here is where the pointer is made. You are giving it no value, so it will have some random value - the random value is the location of the memory it is pointing to, so it's just pointing at some random memory somewhere. Could be anywhere.

And that's it. You never make it point to some memory. You never give this pointer a value, so when you write into the memory it points at, you are writing into some random memory somewhere. This is very, very bad. Do not write data into memory at random. If you are lucky, the random memory will be something the OS doesn't want you writing into and will segFault. If you are unlucky, it will be data that does belong to you, so the OS won't stop you and you will write over your own data.

I suspect you don't understand pointers. http://www.cplusplus.com/articles/EN3hAqkS/
Last edited on
Moschops.

Thanks for pointing that out. No pun intended.

Here is my solution to the problem:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
DWORD SELECT_ELEMENT() {

	char* elements[] = { "fire", "water", "air", "earth" };
	char** e=elements;
	int SelectedElement = '\0';
	char selectedElement[10];

	cout << "Which element do you want control of?" <<endl;
	cin.getline(selectedElement, 10);

	for(int i=0; i<4; i++)
	{
		if(strcmp(e[i], selectedElement)==0) {
			cout << "Match found.";
			 SelectedElement = i;
			break;
		}
	}
	if(SelectedElement=='\0') { 
		cout << "No match found."<<endl;
	} else {
		return SelectedElement;
	}
}


I'll probably need to read some things again, Thanks.
Topic archived. No new replies allowed.