指针和内存
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
typedef struct tray
{
char color[ 10 ];
int id;
}TRAY;
int top = -1;
TRAY* trays[ SIZE ];
TRAY *pop ( void );
TRAY *push( TRAY tr);
void get_data( TRAY* ptr );
void put_data( const TRAY* ptr );
void main()
{
int ans , flag;
TRAY t ;
TRAY *ptr;
do
{
do
{
printf( "\n\n\tEnter 1 to push , 2 to pop:" );
scanf( "%d", &ans);
printf( "\n" );
switch( ans )
{
case 1:
get_data( &t );
if( push( t ) == NULL )
printf( "\n\n STACK FULL!\n\n" );
break;
case 2:
if( ( ptr = pop() ) != NULL )
put_data( ptr );
else
printf( "\n\nSTACK EMPTY\n\n" );
break;
default:
printf( "\nillegal response\n" );
break;
}
}while( ans != 1 && ans != 2 );
printf( "\n\n\n1 to continue, 0 to quit:" );
scanf( "%d", &flag );
printf( "\n" );
}while( flag );
}
void get_data( TRAY* ptr )
{
printf( "\nEnter the tray's color: " );
scanf( "%s", ptr -> color );
printf( "\nEnter the tray's id: " );
scanf( "%d", ptr -> id );
printf( "\n" );
}
void put_data( const TRAY* ptr )
{
printf( "\ntray's color :%s\n" , ptr -> color );
printf( "\ntray's id :%d\n" , ptr -> id );
}
TRAY *push( TRAY tr )
{
TRAY* ptr = NULL;
if( top >= SIZE - 1 )
return NULL;
ptr = malloc( sizeof( TRAY ) );
strcpy(ptr ->color , tr.color);
ptr ->id = tr.id;
trays[ ++top ] = ptr;
return ptr;
}
TRAY *pop ( void )
{
static TRAY popped_tray;
if( top < 0 )
return NULL;
popped_tray = *trays[ top ];
free( trays[ top-- ] );
return &popped_tray;
}
用VC编译,运行的时候说指令引用了0xcccccccc,不能为"written"的位置