什么是malloc的这个code在做什么? [英] What is malloc doing in this code?
问题描述
你能否说明在code?
海峡=(字符*)malloc的(的sizeof(字符)*(NUM + 1));
- 什么是
的malloc
在这里做什么? - 为什么
NUM + 1
使用吗?
的malloc
是分配的堆内存块,并返回一个<一个函数 HREF =http://en.wikipedia.org/wiki/Pointer%5F%28computing%29>指针它。这是类似于新
运营商在许多语言。在这种情况下,它的创建的内存块可存活的任意时间长度并具有任意的大小。这本身是相当深入的东西,这有点难以解释并保证一个单独的问题。
的 NUM + 1
补偿空终止对字符串的结束。字符串经常需要知道他们有多长,而C的传统是对字符串,它永远是特殊字符的末尾附加字符分配房间 \\ 0
。允许以字符串处理功能,以自动确定字符串的大小。例如,如果你想做些什么来字符串的每个字符不知道该字符串有多长,你可以做这样的事情:
为const char * PTR = str中;
而(* PTR!='\\ 0'){
流程(* PTR);
PTR ++;
}
Could you explain following code?
str = (char *) malloc (sizeof(char) * (num+1));
- What is
malloc
doing here? - Why is
num + 1
used?
malloc
is a function that allocates a chunk of memory on the heap and returns a pointer to it. It's similar to the new
operator in many languages. In this case, it's creating a block of memory that can survive for an arbitrary length of time and have an arbitrary size. That in itself is fairly in-depth stuff, which is somewhat difficult to explain and warrants a separate question.
The num + 1
compensates for the null terminator on the end of strings. Strings often need to know how long they are, and the C tradition is to allocate room for an additional character on the end of the string, which will always be the special character \0
. That allows functions that deal with the string to determine the size of the string automatically. For example, if you wanted to do something to every character of a string without knowing how long the string is, you could do something like this:
const char *ptr = str;
while (*ptr != '\0') {
process(*ptr);
ptr++;
}
这篇关于什么是malloc的这个code在做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!