Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allocate the array before calling strcpy?

Tags:

c

string

Given:

char test[] = "bla-bla-bla";

Which of the two is more correct?

char *test1 = malloc(strlen(test));
strcpy(test1, test);

or

char *test1 = malloc(sizeof(test));
strcpy(test1, test);
like image 973
LLL Avatar asked Sep 12 '10 14:09

LLL


2 Answers

This will work on all null-terminated strings, including pointers to char arrays:

char test[] = "bla-bla-bla";
char *test1 = malloc(strlen(test) + 1);
strcpy(test1, test);

You won't get the correct size of the array pointed to by char* or const char* with sizeof. This solution is therefore more versatile.

like image 180
Tomasz Kowalczyk Avatar answered Nov 03 '22 18:11

Tomasz Kowalczyk


Neither:

#include <string.h>
char *mine = strdup(test);
like image 31
Matt Joiner Avatar answered Nov 03 '22 17:11

Matt Joiner