如何解决C ++:指向char指针的char指针指向char数组的指针
我将竭尽所能: 因此,我有一个作业要创建“单词表”类。我将在其中存储单词列表。 这些是成员变量
class WordList
{ //...
unsigned int m_count; // Number of words currently in list
unsigned int m_max; // The total size of the list.
char** m_list; // The list storing the words
};
这是我的构造函数
WordList::WordList(const int max_words) {
if(max_words < 1){
m_list = nullptr;
m_max = 0;
m_count = 0;
}
else
m_list = new char*[max_words];
m_count = 0;
m_max = max_words;
for (int i = 0; i < max_words; i++) {
m_list[i] = new char[20];
}
}
这是我开始发现问题的地方。
以下add函数应该以c样式字符串的形式添加一个单词,该字符串从**char m_list
指向的字符指针数组中指向。
int WordList::add(const char word[]) {
if (m_count == 0 && m_list != nullptr ) {
strcpy (m_list[m_count],word);
m_count++;
return 0;
}
if (m_count < m_max) {
m_count++;
strcpy (m_list[m_count],word);
return 0;
}
if (m_count == m_max) {
m_count++;
m_max ++;
strcpy (m_list[m_count],word);
return 1;
}
if (strlen(word)==0) {
return -2;
}
if (m_list == nullptr ){
return -2;
}
else
return -2;
}
所以我遇到的问题是,我显然在语法上不正确地使用*,因为我没有得到5个指向完整单词的指针数组,而是将第一个字母保存到最终目标字符中,但是没有复制所有想要的内容。
我确定我并没有把我的问题翻译成英文,但是希望这是一个开始。谢谢!
我将如何调用添加函数的示例:
WordList *wordlist = new WordList(5);
wordlist->add("harry");
wordlist->add("ron");
wordlist->add("hermione");
它应该在指针数组的底部添加一个指向每个单词的指针 所以
cout << wordlist->m_list[0][2] << endl; // Expect 'r'
cout << wordlist->m_list[1] << endl; // Expect "ron"
反而我得到
r
仅打印
解决方法
我没有发现您使用双指针有什么问题。
还有其他问题:
- 在您的
WordList::add
中,您应该首先检查空词或空列表,然后快速失败。此外,在您的代码中,如果单词为空-您已经添加了该单词并从该函数返回了。 - 在
if (m_count < m_max)
块中,您先递增m_count
,将一个元素留空,并有可能在最后一个条目上越界。 - 在
if (m_count == m_max) {
中,您确实越界了 - 建议:与其预先分配20个字符的数组,不如
nullptr
;当您需要输入单词时-使用strdup(word);
会为您分配所需的空间。 - 至于您的
I am getting the first letter saved
-我猜您没有正确检查...
问题是您添加了第一个单词:
if (m_count == 0 && m_list != nullptr ) {
strcpy (m_list[m_count],word);
m_count++;
return 0;
}
将m_count递增,因此现在m_count为1。
然后添加第二个单词:
if (m_count < m_max) {
m_count++;
strcpy (m_list[m_count],word);
return 0;
}
在添加单词之前将m_count递增,以便第二个单词位于索引2处,而索引1被完全跳过。
复制单词后,您必须始终增加计数,因为m_count基于1,数组基于0。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。