将字符串读入字符数组,然后获取字符串的大小

问题描述:

我正在一个项目上工作,我很困惑这部分。将字符串读入字符数组,然后获取字符串的大小

我需要从标准输入读取单词并将它们放置在字符数组中,并使用指针数组指向每个单词,因为它们将呈锯齿状。其中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

如果您使用额外的指针 引用并直接增加,那么您的代码将更易于管理。这样你就不必做任何 心理数学。另外,您需要在 读取下一个字符串之前递增参考,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

你想做什么是相对简单的。你有一个存储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