简体   繁体   English

动态初始化字符数组

[英]initialize character array on the fly

I want to initialize a char array using pointers, on the fly.That is user giving input do not know the size of array.User keeps on giving input until return is pressed.Condition here is to: 我想即时使用指针初始化一个char数组,即用户输入的内容不知道数组的大小,用户一直在输入直到按下回车键,条件是:

  • Use pointers to initialize 使用指针进行初始化
  • Not to pass size of array in advance. 不预先传递数组的大小。

Assuming a C question, how about (untested): 假设有一个C问题,那么(未测试)如何:

char *arr = malloc(10);
size_t size = 10, index = 0;
int ch;
while ((ch = getc(stdin)) != EOF && ch != '\n' && ch != '\r') {
    if (index >= size) {
        size *= 2;
        arr = realloc(arr, size); /* XXX check it first. */
    }
    arr[index++] = ch;
}
arr[index] = 0;

If it's really a C++ question you want std::getline with a std::string . 如果确实是C ++问题,则需要带std::string std::getline

The std::string has a method push_back also std::vector would do the job. std :: string有一个方法push_back std :: vector也可以。 Still if you are REALLY forced to use a dynamic array and char pointers I would advice you to implement reallocation strategy similar to the one used in vector - double the size each time the number of elements is more then the current size. 仍然,如果真的要使用动态数组和char指针,我还是建议您实现类似于vector中使用的重新分配策略-每次元素数量大于当前大小时,将大小增加一倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM