将内存分配给char * C语言 [英] Allocating memory to char* C language
本文介绍了将内存分配给char * C语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是为char *分配内存的正确方法.
Is it the correct way of allocating memory to a char*.
char* sides ="5";
char* tempSides;
tempSides = (char*)malloc(strlen(inSides) * sizeof(char));
推荐答案
几乎.字符串以NULL终止,因此您可能想分配一个额外的字节来存储NULL字节.也就是说,即使sides
为1个字符长,它实际上还是2个字节:{5
,'\0'
}.
Almost. Strings are NULL terminated, so you probably want to allocate an extra byte to store the NULL byte. That is, even though sides
is 1 character long, it really is 2 bytes: {5
,'\0'
}.
应该是:
tempSides = (char *)malloc((strlen(sides)+1)*sizeof(char));
,如果您想将其复制到:
and if you wanna copy it in:
strcpy(tempSides, sides);
这篇关于将内存分配给char * C语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文