可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Trying to copy a char *str
to char c[]
but getting segmentation fault or invalid initializer error.
Why is this code is giving me a seg fault?
char *token = "some random string"; char c[80]; strcpy( c, token); strncpy(c, token, sizeof c - 1); c[79] = '\0'; char *broken = strtok(c, "#");
回答1:
use strncpy()
rather than 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; }
回答2:
char *str = "Hello"; char c[6]; strcpy( c, str );
回答3:
use strncpy to be sure to not copy more charachters than the char[] can contains
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';
Edit: Code added to question
Viewing your code the segmentation fault could be by the line
strcpy(c, token)
The problem is if token length is bigger than c length then memory is filled out of the c var and that cause troubles.
回答4:
char c[] must have some size;
for example
char c[]= "example init string";
// that set up table c to c[19]; You can allocate it directly at the begginign of Your program;
char c[19] = {0}; // null filled table
char c[i] is the pointer so You don't need to copy anything; char c[19] ; c = "example init string"; // now &c[0] points the same address;
Copy can be done wiht
strcpy(dst, src);
but MS force You to use secure function:
strcpy_s(dst,buffsize,src);
回答5:
It's been a while since i coded in c/c++, but c[80] is probably allocated on the stack. If you use char *c and strdup or similiar you get it allocated on the heap where strtok can access it.
Try something like this.
char *token = "some random string"; char *c; c = strdup(token); char *broken = strtok(c, "#"); free(c);
回答6:
Edited: Thanks for adding the code.
Perhaps the segfault occurs here:
strncpy(c, token, sizeof c - 1);
sizeof has a the same precedence as '-' from right to left, so it is probably processed as :
strncpy(c, token, sizeof( c - 1 ) );
instead of
strncpy(c, token, sizeof(c) - 1);
which is probably what you wanted
(reference: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence)