0

我已经尝试了递归和迭代方法,但我一直遇到存储不确定长度的字符串的问题。如果它们是某种库或 Api 调用,它会一直读取到下一个空格,这将证明非常有用。

但本质上,我需要创建一个包含字符数组的结构数组。

4

2 回答 2

2

使用 malloc 和 realloc 为您的输入腾出空间。选择一个合理的起始大小(您必须对预期有多少字符有所了解)。每次重新分配时,将大小加倍。

于 2013-02-06T02:18:20.137 回答
1

我想这个例子显示了你在寻找什么。我建议玩弄mallocfree发现它的行为。goto还要阅读 goto 的评论,除非你真的知道你在做什么,否则不要使用。使用它,您可能会非常容易失败。一个while带有 if 的循环来检查缓冲区是否溢出下一个字符会更好,但我很懒所以我保持原样。如果您还有任何问题,请询问。

#include <malloc.h>
#include <string.h>

int main( ) {
  unsigned bufferSize = 0; // our array size
  int i = 0; // current position in buffer
  // we allocate memory for our buffer
  char *buffer = (char *)malloc( bufferSize += 10 );

  int ch = EOF; // set to eof, we will use this to buffer input

  // read input until buffer is full
repeat_input:
  for( ; i < bufferSize; i++ ) { // a while loop would be better for this job...
    ch = fgetc( stdin );
    if( ch == ' ' ) {
      // if there is a space we can break here
      goto done; // this is bad coding practice, i am just a bit lazy now
    }
    buffer[ i ] = ch;
  }

  // keep our old buffer pointer to not create a memleak
  char *old_buffer = buffer;
  buffer = (char *)malloc( bufferSize += 10 );

  // copy content of old buffer to new one
  int k = 0;
  for( k = 0; k <= i; k++ ) {
    buffer[ k ] = old_buffer[ k ];
  }

  // free RAM, else we have a memleak
  free( old_buffer );
  goto repeat_input;

done:
  fputs( buffer, stderr );
  free( buffer );
  return 1;
}
于 2013-02-06T02:03:53.177 回答