[英]Allocating Memory for string in c?
How do i allocate the memory for a given char array *bla in c? 如何在C中为给定的char数组* bla分配内存?
blaarray = (char*)malloc(strlen(bla)*sizeof(bla));
or 要么
blaarray = (char*)malloc(strlen(bla)*sizeof(char*));
or neither? 还是都不?
thanks 谢谢
**note edits to reflect silly typo. **注意编辑内容以反映愚蠢的错字。 I accidently pasted the options incorrectly
我不小心将选项贴错了
If you want blaarray
to be of the same size as the string bla
如果您希望
blaarray
与字符串bla
具有相同的大小
blaarray = malloc((strlen(bla)+1) * sizeof(char));
Now let me explain some points. 现在让我解释一些观点。
1) To get the length of a string, use only strlen()
not sizeof
1)要获取字符串的长度,请仅使用
strlen()
而不使用sizeof
2) 1
has to be added because strlen()
does not include the \\0
character while returning the length 2)必须添加
1
,因为strlen()
在返回长度时不包含\\0
字符
3) char*
is a pointer to char
, to get size of a char
, one should do sizeof(char)
3)
char*
是指向char
,得到的大小char
,一个应该做sizeof(char)
4) Off course you need to declare blaarray
, which you can do like 4)当然,您需要声明
blaarray
,您可以这样做
char* blaarray;
5) You do not need to cast the return of malloc()
, see this . 5)您不需要
malloc()
的返回值,请参阅this 。
6) sizeof(char)
is 1, so you can skip that. 6)
sizeof(char)
为1,因此可以跳过。
So, all in all your code should look like. 因此,所有代码都应该看起来像。
char* blaarray;
blaarray = malloc((strlen(bla)+1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.