akr*_*roy 11 c++ string copy cstring
有没有简单的方法来复制C字符串?
我有const char *stringA
,我想char *stringB
取值(注意stringB
不是const
).我试过stringB=(char*) stringA
,但这stringB
仍然指向相同的内存位置,所以当stringA
以后的更改时,stringB
也是如此.
我也试过strcpy(stringB,stringA)
,但似乎如果stringB
没有初始化为足够大的数组,那就是段错误.我对C字符串没有超级经验,我错过了一些明显的东西吗?如果我只是初始化stringB
为char *stringB[23]
,因为我知道我永远不会有一个比22
字符更长的字符串(并允许空终止符),这是正确的方法吗?如果stringB
检查是否与其他C字符串相等,那么额外的空格是否会影响任何内容?
(并且在这里使用字符串不是解决方案,因为我需要最小的开销并且可以轻松访问单个字符)
Ale*_*lds 17
您可以使用strdup()
返回C字符串的副本,如下所示:
#include <string.h>
const char *stringA = "foo";
char *stringB = NULL;
stringB = strdup(stringA);
/* ... */
free(stringB);
Run Code Online (Sandbox Code Playgroud)
您也可以使用strcpy()
,但是您需要先分配空间,这不是很难做但可能导致溢出错误,如果没有正确完成:
#include <string.h>
const char *stringA = "foo";
char *stringB = NULL;
/* you must add one to cover the byte needed for the terminating null character */
stringB = (char *) malloc( strlen(stringA) + 1 );
strcpy( stringB, stringA );
/* ... */
free(stringB);
Run Code Online (Sandbox Code Playgroud)
如果你不能使用strdup()
,我会建议使用strncpy()
而不是strcpy()
.该strncpy()
函数最多复制 - 最多 - 最多 - n
字节,这有助于避免溢出错误.strlen(stringA) + 1 > n
但是,如果你需要stringB
自己终止.但是,一般来说,你会知道你需要什么尺寸的东西:
#include <string.h>
const char *stringA = "foo";
char *stringB = NULL;
/* you must add one to cover the byte needed for the terminating null character */
stringB = (char *) malloc( strlen(stringA) + 1 );
strncpy( stringB, stringA, strlen(stringA) + 1 );
/* ... */
free(stringB);
Run Code Online (Sandbox Code Playgroud)
我认为strdup()
更清洁,我自己,所以我尝试使用它专门处理字符串.我不知道POSIX /非POSIX方法是否有严重的缺点,性能方面,但我不是C或C++专家.
请注意,我将结果转换malloc()
为char *
.这是因为您的问题被标记为c++
问题.在C++中,需要从中转换结果malloc()
.但是,在C中,你不会投这个.
编辑
你去,有一个并发症:strdup()
不是C或C++.因此,使用strcpy()
或strncp()
使用预先调整大小的数组或malloc
-ed指针.它是用一个良好的习惯strncp()
,而不是strcpy()
,无论你可能使用该功能.它将有助于减少出错的可能性.
归档时间: |
|
查看次数: |
14392 次 |
最近记录: |