[英]this size to use into malloc() is right?
Assuming that I have char **
where each value of can have an char *
and I need store more bytes to character teminator ( NULL
) how do I to compute this size? 假设我有char **
,其中的每个值都可以有一个char *
并且我需要将更多字节存储到字符终止符( NULL
)中,如何计算该大小? maybe..: sizeof(char *) * strlen(src) + sizeof(NULL)
or only + 1 instead of sizeof(NULL)
? 也许..: sizeof(char *) * strlen(src) + sizeof(NULL)
或仅+1而不是sizeof(NULL)
吗? I hope this is clear for you. 希望对您来说很清楚。 Thanks in advance. 提前致谢。
A char **
is a pointer to a pointer to the first character of a string. char **
是指向字符串第一个字符的指针。 In your example, the memory for the pointer char **out
is already allocated on the stack. 在您的示例中,指针char **out
的内存已在堆栈上分配。 What you have to do is allocate the memory for the character array (C string) which out
points to on the heap. 你必须做的是分配的字符数组(C字符串),它的内存out
点堆中。 That is, you could do something like: 也就是说,您可以执行以下操作:
char **out;
char *str = malloc(strlen(src) * sizeof(char) + 1);
*out = str;
Now you can (for example) safely return out
and pass control of the memory you allocated to the caller. 现在,您可以(例如)安全地out
并传递对分配给调用方的内存的控制权。
If you wanted to return a pointer to the first element of an array of strings (another way of interpreting a char **), you would have to first allocate on the heap enough memory for each string: 如果要返回一个指向字符串数组第一个元素的指针(另一种解释char **的方式),则必须首先在堆上为每个字符串分配足够的内存:
char **out = malloc(amount_of_strings * sizeof(char *));
// Repeat the following for each string in your array...
char *str = malloc(strlen(src) * sizeof(char) + 1);
out[index] = str;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.