c语言 - 我正在尝试使用动态内存分配存储三个员工的 ID



Code -

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *e;
int len;
for (int i = 1; i < 4; i++)
{
printf("Enter the size of the ID of the Employee %dn", i);
scanf("%d", &len);
printf("Enter Employee ID of Employee %dn", i);
scanf("%s", &e);
}
e = (char *)malloc((len + 1) * sizeof(char));
for (int i = 1; i < 4; i++)
{
printf("ID of Employee %d is %sn", i, e);
}
return 0;
}

终端-

Enter the size of the ID of the Employee 1
2
Enter Employee ID of Employee 1
A2
Enter the size of the ID of the Employee 2
2
Enter Employee ID of Employee 2
A7
Enter the size of the ID of the Employee 3
3
Enter Employee ID of Employee 3
AA1

预期输出 -

ID of Employee 1 is A2
ID of Employee 2 is A7
ID of Employee 3 is AA1

我得到的输出 -

»D of Employee 1 is Φ
»D of Employee 2 is Φ
»D of Employee 3 is Φ

在这里,»D 和 Φ 是指每次在另一个终端中运行它时都会更改的垃圾值

我只是在学习动态内存分配的基础知识,但即使在其中也会遇到问题
Pls Help

除了上面的注释之外,您还有一个明显的错误,即您尝试在分配内存之前使用内存。试试这个:

#include <string.h>
#define MAX_EMP 3
int main()
{
char *e[MAX_EMP];
int len[3];
for (int i = 0; i < MAX_EMP; i++)
{
printf("Enter the size of the ID of the Employee %dn", i + 1);
scanf(" %d ", &len[i]);
e[i] = (char*)malloc((len + 1) * sizeof(char));
printf("Enter Employee ID of Employee %dn", i + 1);
scanf(" %s ", e[i]);
}
for (int i = 0; i < MAX_EMP; i++)
printf("ID of Employee %d is %sn", i + 1, e[i]);
return 0;
}

另请注意,内存资源很少如此昂贵,以至于动态内存分配对如此小的字符串有意义。这样做更实用:

#include <string.h>
#define MAX_EMP 3
#define MAX_LEN 10
int main()
{
char e[MAX_EMP][MAX_LEN + 1];
for (int i = 0; i < MAX_EMP; i++)
{
printf("Enter Employee ID of Employee #%dn", i + 1);
fgets(e[i],MAX_LEN + 1,stdin);
}
for (int i = 0; i < MAX_EMP; i++)
printf("ID of Employee #%d is %sn", i + 1, e[i]);
return 0;
}
  • 您需要存储每个员工的数据(可能在数组中)
  • scanf("%s", something)something中必须是char *的类型。在您的代码中,它是char **.
  • 不要使用 scanf %s,因为它假定缓冲区对于输入来说足够大。使用fgets或扫描 %ms
  • 在新版本中,还有scanf("%ms", something)somethingchar **。它分配字符串并将指向它的指针存储在*something
  • 使用数组时,i从 0 开始更容易
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *ids[3];   // store the id for every employee, no need to store the length
for (int i = 0; i < 3; i++)
{
printf("Enter the size of the ID of the Employee %dn", i + 1);
int len;
scanf("%d", &len);
ids[i] = malloc(len + 1);   // no need to cast the pointer, sizeof(char) is always 1
printf("Enter Employee ID of Employee %dn", i + 1);
scanf("%s", ids[i]);   // use fgets here
}
for (int i = 0; i < 3; i++)
{
printf("ID of Employee %d is %sn", i + 1, ids[i]);
free(ids[i]);   // free it when you are done with it
}
return 0;
}

相关内容

最新更新