繁体   English   中英

我不知道为什么,但是用于打印 id 的第二个 for 循环无法正常工作,有时如果我给第三个员工程序退出的长度为 9

[英]I don't know why but the 2nd for loop for printing the id's is not working properly and a sometimes if I give length 9 to 3rd employee program exits

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char *ptr;
    int n;
    printf("This program was created to store Employee's ID data.\nIt can take both alphabet as well as integers as id.\n");
    for (int i = 0; i < 3; i++)
    {
        printf("\nFor Employee No: %d",i);
        printf("\nEnter the size(in number) of your id:");
        scanf("%d",&n);
        ptr=(char*)malloc(n*sizeof(char));
        printf("Enter your id:");
        scanf("%s",&ptr[i]);
    }
    for (int i = 0; i < 3; i++)
    {
        printf("The id of employee number %d is %s\n",i,ptr[i]);
    }
    
    free(ptr);
    return 0;
}

我是新手,因为我刚刚学习了动态 memory 分配的四个功能,并尝试制作这个简单的代码。 但是由于某种原因,我不知道为什么程序没有像我希望的那样运行。

我希望程序获得 3 名员工的 id。 该程序将首先要求他们选择 id 的长度,然后获取他们的 id 并将它们存储在一个变量中。 id 应该能够同时包含字符和整数。 存储它们后,它应该打印它们。
但是第二个 for 循环从不打印,程序显然停止并退出。 请指导我。

  • 您想读取 3 个 ID,因此您应该分配一个char*的 3 元素数组。
  • 您应该(至少)分配比 ID 长度多一个元素来存储终止空字符。
#include <stdio.h>
#include <stdlib.h>
int main()
{
    char *ptr[3]; /* allocate an array of char* */
    int n;
    printf("This program was created to store Employee's ID data.\nIt can take both alphabet as well as integers as id.\n");
    for (int i = 0; i < 3; i++)
    {
        printf("\nFor Employee No: %d",i);
        printf("\nEnter the size(in number) of your id:");
        scanf("%d",&n);
        ptr[i]=(char*)malloc((n+1)*sizeof(char)); /* allocate one more element for terminating null-character and save it to an element of the array */
        printf("Enter your id:");
        scanf("%s",ptr[i]); /* remove an extra & and pass char* for scanf() */
    }
    for (int i = 0; i < 3; i++)
    {
        printf("The id of employee number %d is %s\n",i,ptr[i]);
    }
    
    /* free each elements */
    for (int i = 0; i < 3; i++)
    {
        free(ptr[i]);
    }
    return 0;
}

如果您检查malloc()scanf()的结果,您的代码会更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM