[英]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 循环从不打印,程序显然停止并退出。 请指导我。
char*
的 3 元素数组。#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.