Search code examples
cgetcharputchar

I am using while loop to enter characters one by one(total number of characters to be entered is unknown). How can I store my characters in an array:


User has to input a string of unknown length(<1000). So here I am using while loop, #define, getchar.
What should I do to store the characters simultaneously?

#include <stdio.h>
#define EOL '\n'

int main()
{
    int count=0;
    char c;

    while((c=getchar())!= EOL)// These c's have to be stored.
    {
        count++;
    }

    return 0;
}

EDIT: Sorry I didn't tell this thing earlier. I don't have to waste 1000 bytes if count!=1000. That's why I am not declaring any array of 1000 elements initially.


Solution

  • Implement a dynamically growing array

    1. use calloc() or malloc() to allocate a small memory block - let's say for 10 chars

    2. use realloc() to increase the size of the memory block if needed

    Example:

    #include <stdio.h>
    #include <stdlib.h>
    
    #define EOL '\n'
    
    int main()
    {
        int count = 0;
        int size = 10;
        char *chars = NULL;
        char c;
        
        /* allocate memory for 10 chars */
        chars = calloc(size, sizeof(c));
        if(chars == NULL) {
            printf("allocating memory failed!\n");
            return EXIT_FAILURE;
        }
    
        /* read chars ... */
        while((c = getchar()) != EOL) {
            /* re-allocate memory for another 10 chars if needed */
            if (count >= size) {
                size += size;
                chars = realloc(chars, size * sizeof(c));
                if(chars == NULL) {
                    printf("re-allocating memory failed!\n");
                    return EXIT_FAILURE;
                }
            }
            chars[count++] = c;
        }
    
        printf("chars: %s\n", chars);
    
        return EXIT_SUCCESS;
    }