Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

char

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, "#");
like image 791
Alex Xander Avatar asked Oct 02 '09 10:10

Alex Xander


People also ask

What does char * [] mean in C?

char* is a pointer to a character, which can be the beginning of a C-string. char* and char[] are used for C-string and a string object is used for C++ springs. char[] is an array of characters that can be used to store a C-string.

What is the difference between char * and char [] in C?

The fundamental difference is that in one char* you are assigning it to a pointer, which is a variable. In char[] you are assigning it to an array which is not a variable.

Is char * A string in C?

This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.

Is char * a string?

char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters. So String is an array of chars. We define char in java program using single quote (') whereas we can define String in Java using double quotes (").


2 Answers

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;
}
like image 78
pmg Avatar answered Sep 18 '22 14:09

pmg


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.

like image 32
Patrice Bernassola Avatar answered Sep 22 '22 14:09

Patrice Bernassola