How to copy char *str to char c[] in C?

2019-01-22 22:36发布

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, "#");

标签: c string char
6条回答
可以哭但决不认输i
2楼-- · 2019-01-22 22:57

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)

查看更多
小情绪 Triste *
3楼-- · 2019-01-22 23:00

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楼-- · 2019-01-22 23:04

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);
查看更多
Emotional °昔
5楼-- · 2019-01-22 23:07
char *str = "Hello";
char c[6];
strcpy( c, str );
查看更多
够拽才男人
6楼-- · 2019-01-22 23:15

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);
查看更多
唯我独甜
7楼-- · 2019-01-22 23:23

use strncpy() rather than strcpy()

/* 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;
}
查看更多
登录 后发表回答