P
P
pepl2132018-10-03 20:47:39
C++ / C#
pepl213, 2018-10-03 20:47:39

How to allocate memory for a string of unknown length?

Read from stdin a string (ends with \n) whose length is unknown.
Those. maybe
agdadsgasdfasdf
Or
asjdfhkasljdfhasd.....
I tried to do something like this, but it turns out that when I get a new character, the chars array is redefined.

#include <stdio.h>
#include <malloc.h>


int main(){
  char *chars;
  int c,n=0;
  while((c=getchar()) != '\n'){
    chars = (char*)malloc(++n * sizeof(char));
    chars[n-1] = c;
  }
  printf("%s\n", chars);
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2018-10-03
@jcmvbkbc

How to improve it?

From man scanf :
Those.:
#include <stdio.h>

int main()
{
  char *chars;
  scanf("%m[^\n]",&chars);
  printf("%s\n", chars);
}

S
Sergey Gornostaev, 2018-10-03
@sergey-gornostaev

const unsigned int MAX_LENGTH = 1 * 1024 * 1024;  // Не выделять больше мегабайта памяти
const unsigned int CHUNK_SIZE = 1024;             // Выделять блоками по килобайту

int main() {
    unsigned int str_len = CHUNK_SIZE;
    char *str_ptr = malloc(CHUNK_SIZE);           // Выделяем первый килобайтный блок

    if (str_ptr == NULL)
        err(EXIT_FAILURE, "Не удалось выделить память!\n");

    int c;
    unsigned int i;
    for (i = 0, c = EOF; (c = getchar()) != '\n' && c != EOF; i++) {
        str_ptr[i] = c;

        if (i == MAX_LENGTH) {
            free(str_ptr);
            err(EXIT_FAILURE, "Слишком много входных данных!\n");
        }
        
        if (i == str_len) {                       // Блок заполнен
            str_len = i + CHUNK_SIZE;
            str_ptr = realloc(str_ptr, str_len);  // Расширяем блок на ещё один килобайт
        }
    }
    str_ptr[i] = '\0';                            // Признак конца строки

    printf("%s\n", str_ptr);

    free(str_ptr);
    str_ptr = NULL;

    return EXIT_SUCCESS;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question