为什么薪水未在以下代码中显示在文件中?
其他所有内容都显示在文件中,因为它应该是银行雇员的薪水。
#include <stdio.h>
struct data {
char ide[50], name[50], bname[50], brname[50], con[10], sal[30];
};
int main() {
int n;
printf("Enter number of employees: ");
scanf("%d", &n);
struct data d[n];
for (int i = 1; i <= n; i++) {
printf("Enter data of employee %d\n", i);
printf("1) ID: ");
scanf("%s", d[i].ide);
printf("2) NAME: ");
scanf("%s", d[i].name);
printf("3) SALARY: ");
scanf("%s", d[i].sal);
printf("4) CONTACT: ");
scanf("%s", d[i].con);
printf("5) BANK NAME: ");
scanf("%s", d[i].bname);
printf("6) BRANCH NAME: ");
scanf("%s", d[i].brname);
}
FILE *fp;
fp = fopen("dbms.txt", "w");
for (int i = 1; i <= n; i++) {
fprintf(fp, "1) ID: %s\n2) NAME: %s\n3) SALARY: %s\n4) CONTACT: %s\n5) BANK NAME: %s\n6) BRANCH NAME: %s\n",
d[i].ide, d[i].name, d[i].sal, d[i].con, d[i].bname, d[i].brname);
}
fclose(fp);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C中的数组indice从0而不是1开始,并且为数组声明指定的内容不是最大索引,而是元素数量。
因此,使用数组
struct
将导致OUT-OUT-OUT-OUT-OUT-OUT-OUT-OUT-范围访问。n-1 ,而不是
1
ton
这样:您应该从
0
循环到可变长度数组)例如
struct Data D [n];
可能无法与大数据大小一起使用,因为它可以在堆栈上分配有限的大小。您应该通过malloc()
而在堆上分配内存:您应该添加
#include&lt; stdlib.h&gt;
使用malloc()(和
exit()
)。跳棋可能会说您应该使用
free()
在使用后进行分配的内存,但是。Array indice in C starts from 0, not 1, and what to specify for array declaration is not the maximum index but the number of elements.
Therefore, your loop
for (int i = 1; i <= n; i++)
with the arraystruct data d[n];
will lead to out-of-range access.You should loop from
0
ton-1
instead of1
ton
like this:Also note that VLA (variable-length array) like
struct data d[n];
may not work with large data size because it may be allocated on the stack with limited size. You should allocate memory on the heap viamalloc()
instead like this:You should add
#include <stdlib.h>
to usemalloc()
(andexit()
).Checkers may say that you should use
free()
to deallocate allocated memory after use, but it may not be required in the real world just before end of program execution.