指针和内存

vanchristin 2009-11-24 12:00:46
#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"的位置
...全文
99 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
vanchristin 2009-11-24
  • 打赏
  • 举报
回复
嗯,谢谢楼上三位,分怎么分呢?
只有776了,第三位兄弟,不好意思哈
jernymy 2009-11-24
  • 打赏
  • 举报
回复

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" );
}
lee673 2009-11-24
  • 打赏
  • 举报
回复
在vc里面指针处理不好的时候会出现类似这样的问题,我也遇到过,会调试就好了的。。。
lee673 2009-11-24
  • 打赏
  • 举报
回复
scanf( "%d", &(ptr -> id) );
就是这个问题
。。。
skysoshy 2009-11-24
  • 打赏
  • 举报
回复

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



scanf( "%d", &(ptr -> id) );
skysoshy 2009-11-24
  • 打赏
  • 举报
回复
- -!
scanf没有取变量地址:

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" );
}
skysoshy 2009-11-24
  • 打赏
  • 举报
回复
linux下运行了下, 好像有段错误, 看看再回复, 占位置。。

69,370

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧