- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
这可能有点毫无意义,但我很好奇你们对此有何看法。我正在用指针迭代一个字符串,并想从中提取一个短的子字符串(将子字符串放入一个预先分配的临时数组中)。是否有任何理由在 strncopy 上使用赋值,反之亦然? IE。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{ char orig[] = "Hello. I am looking for Molly.";
/* Strings to store the copies
* Pretend that strings had some prior value, ensure null-termination */
char cpy1[4] = "huh\0";
char cpy2[4] = "huh\0";
/* Pointer to simulate iteration over a string */
char *startptr = orig + 2;
int length = 3;
int i;
/* Using strncopy */
strncpy(cpy1, startptr, length);
/* Using assignment operator */
for (i = 0; i < length; i++)
{ cpy2[i] = *(startptr + i);
}
/* Display Results */
printf("strncpy result:\n");
printf("%s\n\n", cpy1);
printf("loop result:\n");
printf("%s\n", cpy2);
}
在我看来,strncopy 既减少了输入又更易于阅读,但我看到人们提倡循环。有区别吗?这有关系吗?假设这是针对较小的 i (0 < i < 5) 值,并且可以确保空终止。
引用:Strings in c, how to get subString , How to get substring in C , Difference between strncpy and memcpy?
最佳答案
strncpy(char * dst, char *src, size_t len)
有两个特殊的属性:
(strlen(src) >= len)
: 结果字符串不会以 nul 结尾。(strlen(src) < len)
: 字符串的末尾将填充/填充“\0”。第一个属性将强制您实际检查是否 (strlen(src) >= len)
并适本地行动。 (或者用 dst[len-1] = '\0';
粗暴地将最后一个字符设置为 nul,就像上面的 @Gilles 所做的那样)另一个属性不是特别危险,但会溢出很多周期。想象一下:
char buff[10000];
strncpy(buff, "Hello!", sizeof buff);
其中涉及 10000 个字节,其中只需要涉及 7 个字节。
我的建议:
memcpy(dst,src,len); dst[len] = 0;
因为为了安全操作,strncpy() 版本已经需要知道大小(以及对它们的检查!),memcpy() 版本并不比 strncpy() 版本更复杂或更危险。 (从技术上讲,它甚至稍微快一点;因为 memcpy() 不必检查 '\0' 字节)
关于创建 C 子字符串 : looping with assignment operator VS strncopy, 哪个更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12283681/
我从 C 开始,我必须编写一个方法来返回由空格分隔的句子中的每个单词。 到目前为止我有这个: #include #include #define SIZE 100 int nextToken(char
这可能有点毫无意义,但我很好奇你们对此有何看法。我正在用指针迭代一个字符串,并想从中提取一个短的子字符串(将子字符串放入一个预先分配的临时数组中)。是否有任何理由在 strncopy 上使用赋值,反之
我是一名优秀的程序员,十分优秀!