const char * to char error message

Hello, I have recently started to learn from a book, and I am currently copying one of the examples from the book. But it doesnt seem to be working and I do not understand why. I have pasted the code below, the error is coming from this part :

1
2
3
4
5
char *dic[][2] = {
		"pencil" , "A writing instrument",
		"keyboard" , "An input device",
		"", ""
	};


The error I am getting says that "a value of type "const char *" cannot be used to initialize an entity of type char * ". I understand that a constant pointer is one which cannot change the address which it stores. But I am not creating that. Or is that what is created to point at this string table the book is talking about? And if that is the case then what is the problem? If anyone could help, it would be appreciated.




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
 #include <iostream>
#include <cstring>

using namespace std;

int main()
{
	char *dic[][2] = {
		"pencil" , "A writing instrument",
		"keyboard" , "An input device",
		"", ""
	};

	char word[80];
	int i;

	cout << "Enter a word : \n";
	cin >> word;

	for (i = 0; *dic[i][0]; i++)
	{
		if (!strcmp(dic[i][0], word))
		{
			cout << dic[i][1] << "\n";
			break;
		}
	}
	if (!*dic[i][0])
		cout << word << " Not found. \n";

	return 0;
}
Last edited on
So just make it
const char *dic[][2]


> Hello, I have recently started to learn from a book
Which one?
And how old is it?

Older versions of C and C++ were pretty loose with string constants, and you could get away with the kind of code shown.

But nowadays, not so much.
And how old is it?

Yeah its a pretty old book, 2003 i believe
and most compilers will tolerate it if you tell it to use less strict rules, but i don't advise it. Instead, get a newer example / book. Prefer one that uses <string>, not char array or char *.

using arrays will make it shut up about it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

int main()
{

//---------max of  10 words, max 100 length each
char words[10][100] = {  
		"pencil" , "A writing instrument",
		"keyboard" , "An input device",
		"", ""
};

for(int i = 0; i < 5; i++)		
cout << words [i] << endl;
	
	
 }

Last edited on
Topic archived. No new replies allowed.