读书人

明明赋值为0了,却得到别的值!高手给看

发布时间: 2012-02-25 10:01:47 作者: rapoo

明明赋值为0了,却得到别的值!!!高手给看一下
这是一个队列的初始化.
为什么我把类型为SqQueue的L中的front赋值为零,它去等于别的值;
而和front 在同一L中的rear却不会.
#include <stdio.h>
#define QUEUE_INIT_SIZE 10
#define QUEUEINCREMENT 1
typedef struct SqQueue{
int *elem;
int front;
int rear;
int queuesize;
int incrementsize;
}SqQueue; /*the queue definition*/

void InitQueue_Sq(SqQueue Q)
{
Q.elem=(int *)malloc(QUEUE_INIT_SIZE+1);
/*the queue has a bit more than it is used*/
/*there are no elems in the initial queue*/
Q.front=0; /*Q.front=0!!!!!!!!!!!!!!!!!!!!!!*/
Q.rear =0;
Q.queuesize=QUEUE_INIT_SIZE;
Q.incrementsize=QUEUEINCREMENT;
} /*InitQueue_Sq*/
void main()
{ SqQueue L;
InitQueue_Sq(L);
printf( "\nthe L.front is %d ",L.front);
/*to my suprise !! L.front=1383 or othdr value!:O why ??????????????*/
printf( "\nthe L.rear is %d ",L.rear);

}

[解决办法]
void InitQueue_Sq(SqQueue Q)
看看你的参数!

在执行 InitQueue_Sq(SqQueue Q)的时候
系统会在函数里面生成一临时的SqQueue 变量,然后将Q赋值给这个临时变量
函数内所有对Q的操作实际上是对这个临时变量进行操作的

所以, 你init的是那个临时变量, 对于Q, 你什么事情都没有做.
也就是说 L你没有初始化

另外, 我觉得声明最好是: SqQueue *L;
[解决办法]
通过传址的方式,
或者把修改的值返回:
void InitQueue_Sq(SqQueue Q)
{
Q.elem=(int *)malloc(QUEUE_INIT_SIZE+1);
/*the queue has a bit more than it is used*/
/*there are no elems in the initial queue*/
Q.front=0; /*Q.front=0!!!!!!!!!!!!!!!!!!!!!!*/
Q.rear =0;
Q.queuesize=QUEUE_INIT_SIZE;
Q.incrementsize=QUEUEINCREMENT;
} /*InitQueue_Sq*/
==》
SqQueue InitQueue_Sq(SqQueue Q)
{
Q.elem=(int *)malloc(QUEUE_INIT_SIZE+1);
/*the queue has a bit more than it is used*/
/*there are no elems in the initial queue*/
Q.front=0; /*Q.front=0!!!!!!!!!!!!!!!!!!!!!!*/
Q.rear =0;
Q.queuesize=QUEUE_INIT_SIZE;
Q.incrementsize=QUEUEINCREMENT;
return Q; //把Q返回了
} /*InitQueue_Sq*/
[解决办法]
void InitQueue_Sq(SqQueue *Q);

SqQueue L;

InitQueue_Sq(&L);

读书人网 >C语言

热点推荐