簡體   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