Reputation: 259
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:
Upvotes: 0
Views: 869
Reputation: 182649
Assuming a C question, how about (untested):
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
.
Upvotes: 3
Reputation: 70939
The std::string has a method push_back
also std::vector would do the job. 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.
Upvotes: 0