Search code examples
cstringgetchar

*C* Acceptable 2D String input?


Is this an okay way to input strings of digits into a 2D array? I have a few questions regarding the code:

  • The assignment is to input as many strings as the user would like until they enter an empty string. Then I need to tokenize and atoi the strings later on.

  • Would it be better / easier to use 1D array and a char ** to do it?

  • And last, with the char **, if I allocate memory for the strings, do I have to allocate more / different memory for the tokens?

    int strInput ( char string[][], int maxChars )
    {
    int i = 0;
    
    printf("Enter strings of digits. Enter empty string to stop.\n");
    while (( string[i][maxChars] = getchar() )
    {
        printf("Please enter a string of digits:");
        i++;
    }
    string[i] = '\0';
    
    return i;
    }
    

Solution

  • The char string[][] K&R notation is ancient, you ought to use the "new" char** style, indeed.

    Is this an okay way to input strings of digits into a 2D array?

    Definitely no. You are reading char by char rather than digit-string by digit-string, which I assume your intention was.

    Would it be better / easier to use 1D array and a char ** to do it?

    It can be done that way, too, writing some token between the items in the same string. It is basically up to you.

    And last, with the char **, if I allocate memory for the strings, do I have to allocate more / different memory for the tokens?

    Yes, sure, you either allocate a very large memory upfront or you keep reallocating.