0

I can't think, how I should go for. I need to input a long char string, I shouldn't care about the size of a string, and the end of a string is only pressing enter.

My thougths are that I should realloc() my buffer by a value, which return a getline() function. But how should I do that, if buffer waits some memory allocation before filling it?

  1. Allocate some memory for a buffer
  2. Use a getline function for getting symbols and return a value of a inputting char string
  3. If I try to realloc some memory one more time ,I think, it is not necessary because I've already typed my string.

    In conclusion, I need to type a string, then record a string in a buffer by size which return a getline() function.

Can you give a hint, how I need to go for this task, if I'm correct in my thoughts?

Code is below:

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

int getline(char* s, int lim);
int main()
{
    char* buffer;
    size_t bufSize=100;
    int c;
    printf("\t\t\tLong Long string!\n");

    buffer=(char*)malloc(bufSize*sizeof(char));
    if (buffer==NULL)
    {
        perror("Unable to allocate buffer\n");
        exit(1);
    }
    printf("input smth:\n");

    c=getline(buffer,bufSize);

    printf("You typed: %s \n",buffer);

    free(buffer);
        return 0;
}
int getline(char s[], int lim)
{
    int c, i;

      for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
    {
          s[i] = c;
    }

    if (c == '\n')
    {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

Here I just allocate buffer of char with 100*sizeof(char) and give a function getline() bufSize=100. And I can see printf("You typed: %s \n",buffer); only only a string of 100 symbols.

X21
  • 168
  • 2
  • 13
  • If you wish to adapt the size to the exact input, you'll need to go through the input character by character and realloc as needed. But this is premature memory optimization. It is much better practice to statically allocate a chunk "large enough" then deny user input beyond a fixed size. – Lundin Oct 17 '17 at 09:26
  • @WeatherVane Yes, I was really searching for a answer before asking, my mistake, I couldn't find this. Thanks! – X21 Oct 17 '17 at 09:31
  • @Lundin You are right about a fixed size. Agree with you! But I just wanted to try to input a string of unknown legth. Thanks for comment. – X21 Oct 17 '17 at 09:33

0 Answers0