[英]why var.name[i] in this code is printing stationto value
#include<stdio.h>
#include <conio.h>
#include <string.h>
float final(float);
// structure to declare variables to be used in code. // 声明要在代码中使用的变量的结构。
struct tag
{
int n;
int age[50];
int dist;
char name[1][50];
char stfrom[50];
char stto[50];
}var;
void main()
{
int i;
float apcost,f;
char str[50];
char name[10][50];
printf("Enter the number of tickets:\n");
scanf(" %d",&var.n);// Total number of tickets
for(i=0;i<var.n;i++)// This loop will run as many number of tickets.
{
// taking inputs of names with spaces and ages.
printf("Enter name:\n");
scanf(" %[^\n]%*c",name[i]);
strcpy(var.name[i], name[i]);
printf("Enter age:\n");
scanf(" %d",&var.age[i]);
}
printf("\nEnter Station from:\n");
scanf(" %[^\n]%*c",var.stfrom);
printf("Enter Station to:\n");
scanf(" %[^\n]%*c",var.stto);
printf("Enter the distance:\n");
scanf(" %d",&var.dist);
apcost = (var.dist * 3) * var.n;
f = final(apcost);
printf("---------------------------------------------------------------------\n");
printf("---------------The Final Bill-------------------------\n\n\n");
printf("Number of tickets purchased:%d\n\n",var.n);
printf("Names and ages of persons respectively:\n");
for(i=0;i<var.n;i++)
{
puts(var.name[i]); //Here the station is getting printed instead of name.
printf("\n%d\n",var.age[i]);
}
printf("\n\nStation From:");
puts(var.stfrom);
printf("\n\nStation to:");
puts(var.stto);
printf("\n\nTotal cost of tickets:%f\n\n",apcost);
printf("--------------------\n");
printf("The final cost after adding 12% tax:%f\n",f);
}
float final(float apcost)
{
float j,k;
j= (0.12 * apcost);
k= apcost + j;
return k;
}
When I am running the code, and entering the number of tickets as 2, the second name I am entering is not printing in the final bill, instead of that var.stto is printing.当我运行代码并将票数输入为 2 时,我输入的第二个名字没有打印在最终账单中,而不是 var.stto 正在打印。
The issue is in your struct definition:问题出在您的结构定义中:
struct tag
{
int n;
int age[50];
int dist;
char name[1][50];
char stfrom[50];
char stto[50];
}var;
The definition for name is statically defined to hold 1 name, and your code is accessing stfrom
when it tries to write to name[2]
. name 的定义被静态定义为包含 1 个 name,并且您的代码在尝试写入
name[2]
时正在访问stfrom
。 To fix this you'll need to make name
a dynamic variable (making it array size 0) and using malloc
to allocate the correct amount of space for the struct.要解决此问题,您需要将
name
设为动态变量(使其数组大小为 0)并使用malloc
为结构分配正确的空间量。 For example:例如:
struct tag
{
int n;
int age[50];
int dist;
char stfrom[50];
char stto[50];
char name[][50];
};
... ...
struct tag *var = malloc(sizeof(struct tag) + 50*num);
where num
is the number of tickets to buy其中
num
是要购买的门票数量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.