好的,这是结构的定义:
typedef struct {
int first;
int last;
int count;
char * Array [50];
} queue;
我使用另一个函数来初始化它
void initialize(queue * ptr){
ptr=malloc(sizeof(queue));
ptr->first=0;
ptr->last=0;
ptr->count=0;
}
然后我使用printf打印出来,最后打印并计数。这三个都应该是零。然而,我实际得到的是,正如我预期的那样,count是0,但是first& last是两个非常大的奇怪数字,每次运行程序时它们都会改变。谁能告诉我这里有什么问题?谢谢。
答案 0 :(得分:6)
您正在按值传递指针。该函数更改了它接收的参数的副本,但调用者的指针未被修改,可能是未初始化的。
您需要更改函数以获取queue**
并传递要初始化的指针的地址。
或者,您可以返回指针,而不是将其作为参数传递。这是一种更简单的方法。
答案 1 :(得分:3)
假设:
void initialize(queue * ptr);
像这样传递:
queue q; // caller allocates a queue
initialize(&q);
// now q is initialized
此外,它由调用者分配 - 不要malloc它。
// bad
void initialize_bad(queue * ptr){
ptr=malloc(sizeof(queue)); << nope. already created by the caller. this is a leak
ptr->first=0;
ptr->last=0;
ptr->count=0;
}
// good
void initialize_good(queue * ptr){
ptr->first=0;
ptr->last=0;
ptr->count=0;
// ptr->Array= ???;
}
如果您更喜欢malloc,请考虑使用此方法返回新的分配:
queue* NewQueue() {
// calloc actually works in this case:
queue* ptr = (queue*)calloc(1, sizeof(queue));
// init here
return ptr;
}
最终,'错误'是你的实现按值传递一个指针,立即将指针重新分配给一个新的malloc'ed分配,根据需要初始化malloc'ed区域,而不必修改参数,并引入一个泄漏。
答案 2 :(得分:0)
以下是您的程序中最小的更改,可以解决您的问题:
void initialize(queue * * pptr) {
queue * ptr;
ptr=malloc(sizeof(queue));
if (ptr) {
ptr->first=0;
ptr->last=0;
ptr->count=0;
}
/* The assignment on the next line assigns the newly allocated pointer
into memory which the caller can access -- because the caller gave
us the address of (i.e. pointer to) such memory in the parameter
pptr. */
*pptr = ptr;
}
最重要的更改是将queue **
传递给您的初始化函数 - 否则您在调用时更改了queue *
提供的副本作为实际参数initialize()
。通过将指针传递给指针,您可以访问将指针存储在调用者中的原始变量。
我无法抗拒,还添加了对NULL
返回的malloc()
的检查。这并没有解决你的问题,但是我无法发布自己的代码而没有这样做。