我必须制作一个程序,作为输入 a 和 b,作为输入,输入以下形式的行数“a”:“studentId studentName studentPhone”和 b 行,形式为“stId mark1 mark2”马克3”。然后程序输出第一个输入的所有 stid,如果输入 b 中存在相同的 id,则程序除了其 id 外还输出学生标记。
为了正确获取输入,我经历了艰辛的过程,我认为这已经很接近了,但我得到了一个奇怪的行为:在我在第二个输入中输入标记后,第一个输入中的一些学生 ID 似乎发生了变化.
这是我的代码:(这里我尝试只输入学生 ID。http://ideone.com/dBYzwe)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
void chomp(char *s);
struct listA{
int stId;
char stName[19];
char stPhone[12];
};
struct listB{
int stId;
char marks[11];
};
int main(void) {
int i, j, m, n;
scanf("%d%d", &m, &n);
struct listA *a = malloc(sizeof(m * sizeof(struct listA)));
struct listB *b = malloc(sizeof(n * sizeof(struct listB)));
for(i = 0; i < m; i++)
{
scanf("%d", &a[i].stId);
fgets(a[i].stName, 19, stdin);
fgets(a[i].stPhone, 11, stdin);
chomp(a[i].stName);
chomp(a[i].stPhone);
}
for(i = 0; i < m; i++)
printf("%d ", a[i].stId);
for(i = 0; i < n; i++)
{
scanf("%d ", &b[i].stId);
fgets(b[i].marks, 12, stdin);
fflush(stdin);
}
printf("\n");
for(i = 0; i < n; i++)
{
printf("%d ", b[i].stId);
}
printf("\n");
for(i = 0; i < m; i++)
printf("%d ", a[i].stId);
return 0;
}
void chomp(char *s) {
while(*s && *s != '\n' && *s != '\r') s++;
*s = 0;
}
最佳答案
问题出在
struct listA *a = malloc(sizeof(m * sizeof(struct listA)));
struct listB *b = malloc(sizeof(n * sizeof(struct listB)));
m * sizeof(struct listA)
的结果是一个整数,因此当您将其放入 sizeof
时,您得到的是整数的大小,而不是您输入的数字想。您应该将其更改为:
struct listA *a = malloc(m * sizeof(struct listA));
struct listB *b = malloc(n * sizeof(struct listB));
关于c- 获取输入后的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19914425/