bank_name
and location
are not strings but single characters. But you attempt to store a string inside them with %s
. Therefore the program will crash and burn.
سؤال
I wrote this code, but it gives a segmentation fault. The loop works only till the printf statement. Please help me rectify the problem.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *fp;
int n,i;
typedef struct transactions
{
char bank_name;
int amount;
int time; //to be given in the form:1320
char location;
int acc_no;
}transaction;//structure
transaction t;
void main()
{
printf("\nHow many records you would like to insert ? : ");
scanf("%d",&n);
fp=fopen("input.txt","r+");
for(i=0;i<n;i++)
{
printf("\nEnter the transaction details");
scanf("%s%d%d%s%d",t.bank_name,&t.amount,&t.time,t.location,&t.acc_no);
fwrite(&t,sizeof(t),1,fp);
}
fclose(fp);
}
المحلول
نصائح أخرى
You should activate the warnings when you compile...
Using clang:
% clang testt.c -Wall
testt.c:22:1: warning: return type of 'main' is not 'int' [-Wmain-return-type]
void main()
^
testt.c:30:28: warning: format specifies type 'char *' but the argument has type 'int' [-Wformat]
scanf("%s%d%d%s%d",t.bank_name,&t.amount,&t.time,t.location,&t.acc_no);
~~ ^~~~~~~~~~~
testt.c:30:58: warning: format specifies type 'char *' but the argument has type 'int' [-Wformat]
scanf("%s%d%d%s%d",t.bank_name,&t.amount,&t.time,t.location,&t.acc_no);
~~ ^~~~~~~~~~
3 warnings generated.
Using gcc:
% gcc testt.c -Wall
testt.c:22:6: warning: return type of ‘main’ is not ‘int’ [-Wmain]
void main()
^
testt.c: In function ‘main’:
testt.c:30:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%s%d%d%s%d",t.bank_name,&t.amount,&t.time,t.location,&t.acc_no);
^
testt.c:30:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 5 has type ‘int’ [-Wformat=]
I'm sure you can solve the issue by yourself (wrong type).
لا تنتمي إلى StackOverflow