C 中的 printf 不提供任何输出

printf in C does not giving any output

我用 C 写了一个代码来打印员工的身份证号码 (可以是数字和字母的组合)编译器将 ID 号作为输入,但它什么也不打印。起初,我使用 'printf' 但它不起作用,所以我用谷歌搜索最终得到的结果是,在许多系统中,出于性能原因,输出有时会被缓冲。我在以下一些主题中得到了很多可能的答案-

然而,我尝试了所有的可能性(作为初学者,实现可能是错误的),但 none 对我来说是可行的 [给出评论]。我有如下代码。感谢任何帮助。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    int* ptr;
    int m;
    char n;
    printf("Id number of employee 1:\n");
    printf("Enter your id number length\n");
    scanf("%d", &m);
    printf("%d\n", m);
    ptr = (int*) malloc (m *sizeof(int));
    printf("Enter your id number:\n");
    scanf("%s", &n);

    // fflush( stdout );
    // fprintf(stderr, "The id number of emploee 1 is %s", n);
    // setbuf(stdout, NULL);
    // setvbuf(stdout, NULL, _IONBF, 0);
    // setvbuf (stdout, NULL, _IONBF, BUFSIZ);
    // printf("The id number of employee 1 is %s\n", n);

    printf("The id number of employee 1 is %s", n);
    return 0;
}

正如评论区所说“一个字符不能容纳一串字母”。 这里还有其他东西可以制作更好的代码,例如释放分配的内存。 这是如何完成的代码示例:

int main()
{
     char* ptr;
     int m;

     printf("Id number of employee 1:\n");
     printf("Enter your id number length\n");
     scanf("%d", &m);

     ptr = (char*)malloc(m * sizeof(char) + 1);

     if (ptr == NULL) {
         printf("Allocation faild...");
         return 1;
         //you can call main to try again...
     }

     printf("Enter your id number:\n");
     scanf("%s", ptr);

     //scanf is not reliable, you can use a loop to enter all characters 
     //to the char array or validate scanf.
     

     printf("The id number of employee 1 is %s",ptr);
     // dont forget to free the allocated data

     free(ptr);
     
     return 0;
}

一个可行的解决方案是(没有动态内存分配)-

直接把char n改成char n[m],不用指点

另一个可行的解决方案是(使用动态内存分配)-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    int m = 5;
    printf("Id number of employee 1:\n");
    printf("Enter your id number length\n");
    scanf("%d", &m);
    char x[m];
    char *n = x;
    n=(char*)malloc(sizeof(char)*m);
    printf("Enter your id number:\n");
    scanf("%s", n);
    printf("The id number of employee 1 is %s\n", n);
    free(n);
    return 0;
}