簡體   English   中英

C++:字符指針到字符指針數組到字符數組

[英]C++: Char pointer to char pointer array to char array

我會盡量簡短:所以我有一個作業,我正在創建一個“Wordlist”類。 我將在其中存儲一個單詞列表。 這些是成員變量

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

只打印出來

我認為您使用雙指針沒有任何問題。

但還有其他問題:

  1. 在您的WordList::add您應該先檢查空詞或空列表,然后快速失敗。 此外,在您的代碼中,如果單詞為空 - 您已經添加了它並從該函數返回。
  2. if (m_count < m_max)塊中,您預先遞增m_count ,將一個元素留空並冒着在最后一個條目上越界的風險。
  3. if (m_count == m_max) {你肯定越界了
  4. 建議:不要預先分配 20 個字符的數組,而將它們保留為nullptr 當你需要一個詞時 - 使用strdup(word); 這將為您分配所需的空間。
  5. 至於你的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 的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM