Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

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

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] = '';
char *broken = strtok(c, "#");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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] = '';
  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...