尝试将 char *str
复制到 char c[]
但出现段错误或无效初始化错误。
为什么这段代码给我一个段错误?
char *token = "some random string";
char c[80];
strcpy( c, token);
strncpy(c, token, sizeof c - 1);
c[79] = '\0';
char *broken = strtok(c, "#");
最佳答案
/* code not tested */
#include <string.h>
int main(void) {
char *src = "gkjsdh fkdshfkjsdhfksdjghf ewi7tr weigrfdhf gsdjfsd jfgsdjf gsdjfgwe";
char dst[10]; /* not enough for all of src */
strcpy(dst, src); /* BANG!!! */
strncpy(dst, src, sizeof dst - 1); /* OK ... but `dst` needs to be NUL terminated */
dst[9] = '\0';
return 0;
}
关于c - 如何在 C 中将 char *string 复制到 char c[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1508838/