[英]Why doesn't string copy between two char pointers work?
我试图将一个字符串从一个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 *消息是“ helloworld”
char *文本为“测试”
我在malloc之后观看了gdb中的消息。 消息更改为“ / 21F / 002”,但文本仍为“ test”
我在消息之前添加了const
,但是它不起作用。
任何人都可以告诉发生了什么事吗?
谢谢。
问题是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()解决该问题。
您必须为指针消息和文本分配存储空间,然后复制字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.