所以我被要求这么做,我是这样做的:

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

    int main(void)
    {
        int N,i;
        printf("Give the number of char's you want to input.\n");
        scanf("%d",&N);

        char *str = (char*) malloc(N);

        //this segment inputs the char's to the string.
        printf("Input the char's.\n");
        for (i=0;i<N;i++)
        {
           str[i] = getchar();
        }
        str[N] = '\0';
    }

既然我是c区的一名新员工,
我想知道是否有其他更好的方法来做这件事。
提前谢谢。

最佳答案

使用variable length arrays(在C99和后者中允许)或使用dynamic memory allocation。你的方法是使用VLA。您还可以动态地执行此操作:

int N;
printf("Give the number of char's you want to input.\n");
scanf("%d",&N);

char *str = malloc(N+1);

旁注:
main更改为其正确的签名int main(void)
数组索引从C中的cc>开始,初始化0i,而不是0,并将上界设置为1。将i < N循环更改为
for (int i = 0; i < N; i++)
{
     str[i] = scanf(" %c");
}
str[N] = '\0';

H2CO3所建议,不要使用for,尤其是与scanf一起使用。
改为使用grtchar

关于c - 如何声明字符串,使其长度由用户在c中给出?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21063686/

10-12 14:20