我有一个函数接受char*作为其参数之一.我需要操纵它,但保留原始的char*.基本上,我想创建这个char*的工作副本.看起来这应该很容易,但我真的很挣扎.
我的第一个(幼稚)尝试是创建另一个char*并将其设置为等于原始:
char* linkCopy = link;
Run Code Online (Sandbox Code Playgroud)
当然,这不起作用,因为我所做的只是让他们指向同一个地方.
我应该使用strncpy来实现这一目标吗?
我尝试过以下操作,但会导致崩溃:
char linkCopy[sizeof(link)] = strncpy(linkCopy, link, sizeof(link));
Run Code Online (Sandbox Code Playgroud)
我错过了一些明显的东西......?
编辑:我很抱歉,我试图简化示例,但我在第二个示例中留下了一些较长的变量名称.固定.
Joh*_*itb 26
该sizeof
会给你指针的大小.通常为4或8,具体取决于您的处理器/编译器,但不是指向的字符串大小.你可以使用strlen和strcpy:
// +1 because of '\0' at the end
char * copy = malloc(strlen(original) + 1);
strcpy(copy, original);
...
free(copy); // at the end, free it again.
Run Code Online (Sandbox Code Playgroud)
我已经看到一些答案建议使用strdup
,但这是一个posix函数,而不是C的一部分.
Sea*_*ght 16
您可能想看一下strdup(man strdup
)函数:
char *linkCopy = strdup(link);
/* Do some work here */
free(linkCopy);
Run Code Online (Sandbox Code Playgroud)
编辑:因为你需要它是标准的C,所以像其他人指出的那样:
char *linkCopy = malloc(strlen(link) + 1);
/* Note that strncpy is unnecessary here since you know both the size
* of the source and destination buffers
*/
strcpy(linkCopy, link);
/* Do some work */
free(linkCopy);
Run Code Online (Sandbox Code Playgroud)
由于strdup()不在ANSI/ISO标准C中,如果它在编译器的运行时中不可用,请继续使用:
/*
** Portable, public domain strdup() originally by Bob Stout
*/
#include <stdlib.h>
#include <string.h>
char* strdup(const char* str)
{
char* newstr = (char*) malloc( strlen( str) + 1);
if (newstr) {
strcpy( newstr, str);
}
return newstr;
}
Run Code Online (Sandbox Code Playgroud)