wjw吧 关注:28贴子:1,699
  • 0回复贴,共1

l2 q3

收藏回复

  • 116.232.210.*
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tTri
{
    int time;
    int distance;
    char* fromwhere;
    char* towhere;
    char* agency;
} Trip;
Trip* initializeAddress(int time, int distance, char fromwhere[], char towhere[],
 char agency[])
{
    Trip* tri;
    char *a, *b, *c;
if( (tri = (Trip*)malloc( sizeof(Trip) )) == NULL )
 return NULL;
    tri->time = time;
    tri->distance = distance;
    if( (a = (char*)malloc( strlen( fromwhere ) * sizeof(char) )) == NULL )
    {
        free( tri );
        return NULL;
    }
    tri->fromwhere = a;
    strcpy( a, fromwhere );
    if( (b = (char*)malloc( strlen( towhere ) * sizeof(char) )) == NULL )
    {
        free( a );
        free( tri );
        return NULL;
    }
    tri->towhere = b;
    strcpy( b, towhere );
    if( (c = (char*)malloc( strlen( agency ) * sizeof(char) )) == NULL )
    {
        free( a );
        free( b );
        free( tri );
        return NULL;
    }
    tri->agency = c;
    strcpy( c, agency );
}
void freeAddress(Trip* tri)
{
    free( tri->fromwhere );
    free( tri->towhere );
    free( tri->agency );
    free( tri );
}
int main()
{
    Trip* myTri;
if( (myTri = initializeAddress( 10, 1000, "Shanghai", "Beijing","CHUN QIU" )) != NULL )
    {
        printf("My Trip is:\n time(day): %d\n distance(Km) : %d\n fromwhere: %s\n towhere: %s\n agency: %s\n",
              myTri->time, myTri->distance, myTri->fromwhere,myTri->towhere, myTri->agency);
        freeTrip( myTri );
}
else printf("Error: Can’t allocate memory!\n");
    return 0;
}


1楼2009-12-01 21:35回复