2013-03-20 160 views
1

我正在一個項目上工作,我很困惑這部分。將字符串讀入字符數組,然後獲取字符串的大小

我需要從標準輸入讀取單詞並將它們放置在字符數組中,並使用指針數組指向每個單詞,因爲它們將呈鋸齒狀。其中numwords是一個int,表示單詞的數量。

char words[10000]; 
    char *wordp[2000]; 

問題是我只能使用指針來添加單詞。我不能再使用[]來幫助。

*wordp = words; //set the first pointer to the beginning of the char array. 
    while (t < numwords){ 
     scanf("%s", *(wordp + t)) //this is the part I dont know 
     wordp = words + charcounter; //charcounter is the num of chars in the prev word 
     t++; 
    } 

    for(int i = 0;words+i != '\n';i++){ 
     charcounter++; 
    } 

任何幫助將是偉大的我很困惑,當涉及到指針和數組。

+2

'wordp = words'甚至不會編譯。向我們展示您的真實代碼。 – 2013-03-20 22:29:27

+0

我知道這不會編譯多數民衆贊成在這個問題,我完全失去了我不知道如何做到這一點 – 2013-03-20 22:36:27

+1

你有10,000個單詞嗎?或者_really_長串? (你已經宣佈了後者)。下一行聲明瞭2000個指針。 – teppic 2013-03-20 22:38:52

回答

1

如果您使用額外的指針 引用並直接增加,那麼您的代碼將更易於管理。這樣你就不必做任何 心理數學。另外,您需要在 讀取下一個字符串之前遞增參考,scanf不會爲您移動指針。

char buffer[10000]; 
char* words[200]; 

int number_of_words = 200; 
int current_words_index = 0; 

// This is what we are going to use to write to the buffer 
char* current_buffer_prt = buffer; 

// quick memset (as I don't remember if c does this for us) 
for (int i = 0; i < 10000; i++) 
    buffer[i] = '\0'; 

while (current_words_index < number_of_words) { 

    // Store a pointer to the current word before doing anything to it 
    words[current_word_index] = current_buffer_ptr; 

    // Read the word into the buffer 
    scanf("%s", current_buffer_ptr); 

    // NOTE: The above line could also be written 
    // scanf("%s", words[current_word_index]); 

    // this is how we move the buffer to it's next empty position. 
    while (current_buffer_ptr != '\n') 
     current_buffer_ptr++; 

    // this ensures we don't overwrite the previous \n char 
    current_buffer_ptr++; 

    current_words_index += 1; 
} 
+0

謝謝,這將幫助我這麼多! – 2013-03-20 23:06:46

1

你想做什麼是相對簡單的。你有一個存儲10000個char的數組,以及2000個指針。所以先從你要第一個指針分配給數組的開始:

wordp[0] = &words[0]; 

在指針的形式是這樣的:

*(wordp + 0) = words + 0; 

我用零來顯示它是如何涉及陣列。在一般情況下,每個指針設置爲每個元素:

*(wordp + i) == wordp[i] 
words + i == &words[i] 

因此,所有你需要做的就是保持跟蹤你是指針數組在的,只要你正確地分配,指針數組跟蹤您在char陣列中的位置。

+0

Oh gotcha非常感謝這麼多的指針,我很難圍繞在我的頭上 – 2013-03-20 23:14:19

+1

@D_Man - 他們可能很難。只要記住一個指針保存一個地址,並且數組中的任何元素在內存中都有一個地址,所以可以指向它。我還修正了上面的東西(愚蠢)錯字。 – teppic 2013-03-20 23:20:56

相關問題