我正在尝试将字符串从一个char *复制到另一个char *,并且不知道为什么副本不起作用。
我正在编写链接列表程序 - Linklist
- 并且涉及两个char *
指针。每个都指向struct Node
,如下所示:
struct Node
{
char * message;
char * text;
struct Node * next;
};
typedef struct Node * Linklist;
我编写了一个函数,它有两个参数来创建一个新的LinkNode
:
Linklist create(char *message,char * text)
{
Linklist list =(Linklist)malloc(sizeof(struct Node));
//the message changes after the sentence but text is right.
if(list==NULL) printf("error:malloc");
list->message=message;
list->text=text;
return list;
}
主要:
char * message是“helloworld”
char * text是“test”
我在malloc之后看了gdb中的消息。消息更改为“/ 21F / 002”,但文本仍为“test”
我在消息之前添加了const
,但它不起作用。
任何人都可以知道发生了什么吗?
感谢。
答案 0 :(得分:4)
问题是c中的字符串不能以相同的方式工作。以下是复制字符串的方法:
Linklist create(char *message,char * text)
{
Linklist list =(Linklist)malloc(sizeof(struct Node));
//the message changes after the sentence but text is right.
if(list==NULL) printf("error:malloc");
list->message = malloc(strlen(message)+1);
if(list->message==NULL) printf("error:malloc");
strcpy(list->message,message);
list->text = malloc(strlen(text)+1);
if(list->text==NULL) printf("error:malloc");
strcpy(list->text,text);
return list;
}
当然,您必须小心,确保消息和文本不是来自用户,否则您可能会面临缓冲区溢出漏洞。
您可以使用strncpy()来解决该问题。
答案 1 :(得分:2)
您必须为指针消息和文本分配存储空间,然后复制字符串。