Array with undefined length in C

后端 未结 3 486
半阙折子戏
半阙折子戏 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:37

    Do not create an array of undefined length.

    After getting the needed length N, if C99 use a VLA (Variable Length Array)

    int A[N];
    

    ... or allocate memory

    int *A = malloc(sizeof *A * N);
    ...
    // use A
    ...
    free(A);
    

    [Edit]

    Good to add validation on N before proceeding. Example:

    if (N <= 0 || N >= Some_Sane_Upper_Limit_Like_1000) return;
    

提交回复
热议问题