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

时间:2013-03-20 22:28:03

标签: c arrays pointers char stdin

我正在研究一个项目,我对这部分感到困惑。

我需要从stdin中读取单词并将它们放在char数组中并使用指针数组指向每个单词,因为它们会被锯齿状。其中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 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

你想做的事情相对简单。你有一个10,000 char的数组用于存储和2000指针。因此,首先,您需要将第一个指针指向数组的开头:

wordp[0] = &words[0];

在指针形式中,这是:

*(wordp + 0) = words + 0;

我用零来显示它与数组的关系。通常,要将每个指针设置为每个元素:

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

所以你需要做的就是跟踪你在指针数组中的位置,只要你正确分配,指针数组就会跟踪char数组中的位置。 / p>