【发布时间】:2021-03-12 12:20:56
【问题描述】:
这是一个关于从堆栈中推送字符串和弹出字符串的代码,字符串名称必须是固定的(不是用户输入的)。但是代码无法运行(它无法显示任何内容)。关键是因为strcpy(temp->id,val);,如果我去掉strcpy(temp->id,val);,那么代码可以正常运行(但是printf 不可读的字符)。我可以知道我的strcpy 有什么问题吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct LLNode
{
char id[4];
struct LLNode *next;
};
struct LLNode * createNode(char val[])
{
struct LLNode *temp;
temp=(struct LLNode *)malloc(sizeof(struct LLNode));
strcpy(temp->id,val);
temp-> id[4] = val;
temp-> next = NULL;
return (temp);
};
char push(char val[], struct LLNode *head)
{
struct LLNode *temp;
temp = createNode(val);
temp->next = head->next;
head->next = temp;
};
char pop(struct LLNode *head)
{
struct LLNode *temp;
char val;
val = head->next->id;
temp = head->next;
head->next = head->next->next;
free(temp);
return(val);
};
int main()
{
char value;
struct LLNode *head = NULL;
struct LLNode *tail = NULL;
struct LLNode *curr;
head = createNode('\0');
tail = createNode('\0');
char id[6][4] = {"A123","B234","C345","D456","E567","F678"};
int n;
for (int i=0;i<6;i++)
{
push(id[i],&head->id);
printf("%s\n",&head->id);
}
};
【问题讨论】:
-
您的
id字段和数组没有足够的空间容纳空终止符。 -
head = createNode('\0');- 无效,编译器应该警告你。此函数需要一个字符串,但您传递单个char。替换为head = createNode(""); -
@EugeneSh。是的,我已替换,但代码仍显示空结果(带有
strcpy(temp->id,val);)或不可读的字符(不带strcpy(temp->id,val);)只是为了确保我的strcpy(temp->id,val);正确吗?
标签: c string stack push strcpy