如何在C中将char * str复制到char c ?

尝试将char *str复制到char c[]但是会出现分段错误或初始化程序错误。

为什么这段代码给我一个seg错误

 char *token = "some random string"; char c[80]; strcpy( c, token); strncpy(c, token, sizeof c - 1); c[79] = '\0'; char *broken = strtok(c, "#"); 

使用strncpy()而不是strcpy()

 /* code not tested */ #include  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; } 
 char *str = "Hello"; char c[6]; strcpy( c, str ); 

使用strncpy确保不要复制比char []可以包含的更多的字符串

 char *s = "abcdef"; char c[6]; strncpy(c, s, sizeof(c)-1); // strncpy is not adding a \0 at the end of the string after copying it so you need to add it by yourself c[sizeof(c)-1] = '\0'; 

编辑:代码已添加到问题中

查看代码可能会出现分段错误

 strcpy(c, token) 

问题是如果令牌长度大于c长度,则从c var中填充内存并导致麻烦。

char c []必须有一些大小;

例如

 char c[]= "example init string"; 

//将表c设置为c [19]; 您可以直接在您的程序的开头分配它;

 char c[19] = {0}; // null filled table 

char c [i]是指针,所以你不需要复制任何东西; char c [19]; c =“example init string”; // now&c [0]指向同一地址;

复制可以完成

  strcpy(dst, src); 

但MS强制你使用安全function:

 strcpy_s(dst,buffsize,src); 

我用c / c ++编写了一段时间,但c [80]可能是在堆栈上分配的。 如果你使用char * c和strdup或类似的,你可以在堆上分配strtok可以访问它。

尝试这样的事情。

 char *token = "some random string"; char *c; c = strdup(token); char *broken = strtok(c, "#"); free(c); 

编辑:感谢您添加代码。

也许这里发生了段错误:

 strncpy(c, token, sizeof c - 1); 

sizeof从右到左具有与’ – ‘相同的优先级,因此它可能被处理为:

 strncpy(c, token, sizeof( c - 1 ) ); 

代替

 strncpy(c, token, sizeof(c) - 1); 

这可能是你想要的

(参考: http : //en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence )