如何分配调用strcpy的前阵? [英] How to allocate the array before calling strcpy?
本文介绍了如何分配调用strcpy的前阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设:
字符测试[] =喇嘛喇嘛喇嘛;
这两个是比较正确的?
的char * TEST1 =的malloc(strlen的(测试));
的strcpy(TEST1,测试);
或
的char * TEST1 =的malloc(sizeof的(测试));
的strcpy(TEST1,测试);
解决方案
这将工作在所有空值终止字符串,其中包括指向字符
数组:
字符测试[] =喇嘛喇嘛喇嘛;
字符* TEST1 =的malloc(strlen的(测试)+ 1);
的strcpy(TEST1,测试);
您不会得到数组的正确尺寸由的char *指向
或为const char *
与的sizeof
。因此更通用这种解决方案。
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);
解决方案
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.
这篇关于如何分配调用strcpy的前阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文