什么是malloc的这个code在做什么? [英] What is malloc doing in this code?

查看:131
本文介绍了什么是malloc的这个code在做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能否说明在code?

 海峡=(字符*)malloc的(的sizeof(字符)*(NUM + 1));


  1. 什么是的malloc 在这里做什么?

  2. 为什么 NUM + 1 使用吗?


解决方案

的malloc 是分配的堆内存块,并返回一个<一个函数 HREF =htt​​p://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));

  1. What is malloc doing here?
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆