簡體   English   中英

為什么這段代碼中的 var.name[i] 打印 stationto 值

[英]why var.name[i] in this code is printing stationto value

#include<stdio.h>
#include <conio.h>
#include <string.h>
float final(float);

// 聲明要在代碼中使用的變量的結構。

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;
}

當我運行代碼並將票數輸入為 2 時,我輸入的第二個名字沒有打印在最終賬單中,而不是 var.stto 正在打印。

問題出在您的結構定義中:

struct tag
{
    int n;
    int age[50];
    int dist;
    char name[1][50];
    char stfrom[50];
    char stto[50];
}var;

name 的定義被靜態定義為包含 1 個 name,並且您的代碼在嘗試寫入name[2]時正在訪問stfrom 要解決此問題,您需要將name設為動態變量(使其數組大小為 0)並使用malloc為結構分配正確的空間量。 例如:

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);

其中num是要購買的門票數量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM