Array with undefined length in C

后端 未结 3 494
半阙折子戏
半阙折子戏 2021-01-21 09:12

i was watching an exercise in my textbook that says: Create a C program that take from the keyboard an array with length \"N\".

The question is: In C language, how can i

3条回答
  •  时光取名叫无心
    2021-01-21 09:41

    It is not easy to satisfy 100% your needs, but you can give it a try:

    #include 
    #include 
    #include 
    
    char *addMe(void);
    
    int main(void){
        char *test = addMe();
        free(test);
        return 0;
    }
    
    char *addMe(void){
        unsigned int maxLength = 15;
        unsigned int i =0;
    
        char *name;
        int c;
    
        name = malloc(1);
        if(name == NULL){
            exit(1);
        }
    
        printf("Enter your name:>  ");
    
        while ((c = getchar()) != '\n' && c != EOF) {
            name[i++] = (char) c;
    
            if (i > maxLength) {
                printf("Names longer than %d not allowed!\n",maxLength);
                name[maxLength] = '\0';
                break;
            }else if (i < maxLength){
                name = realloc(name, maxLength + 2);
            }
        }
    
        name[i] = '\0';
        printf("Your name is:>  %s\nThe length is:>  %zu\n",name ,strlen(name));
    
        return name;
    }
    

    Output:

    Enter your name:>  l
    Your name is:>  l
    The length is:>  1
    

    As you probably noticed I allocated memory only for one letter, and if you need more it will be allocated to satisfy your needs. You can also with this approach to have control of a maximum size:

    Enter your name:>  Michael jacksonnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
    Names longer than 15 not allowed!
    Your name is:>  Michael jackson
    The length is:>  15
    

    Like I said, give it a try.

提交回复
热议问题