我有一个使用结构的堆栈。我需要在弹出时返回一个字符串。所以我尝试使用 strcpy() 将字符串复制到指针,但是当我运行程序时,程序在该步骤停止工作。
这是堆栈的代码。
struct node{ // stack structure
char data[5];
struct node *link;
}*top=NULL;
这是 pop 函数的代码。
char* pop(){
printf("\nIn pop fun.");
if(top==NULL)
{
printf("Error!!!\nStack Underflow.");
return "error";
}
printf("\nChecked if pop is null.");
char *popvar;
printf("\nCreated new char pointer.");
strcpy(popvar,top->data);
printf("\nCopied data from top.");
struct node *tmp = top;
printf("\nCreated new node.");
top=tmp->link;
printf("\n Assigned top new value.");
free(tmp);
printf("\nFree temp");
printf("\npoped from stack.");
return popvar;
}
请大家帮忙...
最佳答案
您不能通过strcpy()
或其他方式写入未初始化的指针。这是写入未定义的内存地址,因此行为未定义。
如果您将 strcpy()
声明为一个数组,那么这是合法的:
char popvar[5];
strcpy(popvar, top->data);
或者一个结构节点
,它有一个数组(而不是指针)成员:
struct node popvar;
strcpy(popvar.data, top->data);
不过,如果不再次复制这些值,则无法将这些值返回给 pop()
的调用者。为此,您可以分配动态(堆)内存:
char *popvar = malloc(5);
strcpy(popvar, top->data);
top = top->link;
return popvar;
在这种情况下,调用者必须始终记住对此结果调用free()
。每个 malloc()
最后必须跟一个 free()
,否则就会出现内存泄漏。请注意,您的原始程序调用 free()
而从未调用 malloc()
;这是非法的,其行为未定义。
另一种可能性是要求调用者决定如何存储结果:
void pop(char *result) {
strcpy(result, top->data);
top = top->link;
}
此函数允许以下任一用途:
char str[5];
pop(str);
或者:
char *str = malloc(5);
pop(str);
/* do stuff */
free(str);
或者甚至:
struct {
int foo;
int bar;
char other_data[5];
} some_other_structure;
pop(some_other_structure.other_data);
关于无法从c中的堆栈结构复制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52441064/