如何为指向 char * 数组的指针分配内存?
有人可以解释一下如何在c中为指向字符指针数组的指针正确分配内存吗?例如:
char *(*t)[];
我尝试这样做:
*t = malloc( 5 * sizeof(char*));
这给了我一个编译错误:
error: invalid use of array with unspecified bounds
对此的任何帮助都会很棒!谢谢
Could someone please explain how to correctly allocate memory for for a pointer to an array of pointer of characters in c? For example:
char *(*t)[];
I try to do it like this:
*t = malloc( 5 * sizeof(char*));
This gives me a compile error:
error: invalid use of array with unspecified bounds
Any assistance on this would be great! Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以做的是:
分配指针数组。
这为数组的每个元素指向的文本分配内存。
What you can do is:
That allocates the array of pointers.
That allocates memory for the text that each element of the array points to.
当人们说“指向 X 数组的指针”时,通常他们实际上指的是指向 X 数组的第一个元素。在 C 中使用数组指针类型非常笨拙,通常只出现在多维数组的使用中。
话虽如此,您想要的类型只是
char **
:使用指向数组的指针类型,它看起来像:
请注意,这将是一个 C99 可变长度数组类型,除非
num_elems
是一个正式意义上的整数常量表达式。When people say "a pointer to an array of X", usually they really mean a pointer to the first element of an array of X. Pointer-to-array types are very clunky to use in C, and usually only come up in multi-dimensional array usage.
With that said, the type you want is simply
char **
:Using a pointer-to-array type, it would look like:
Note that this will be a C99 variable-length array type unless
num_elems
is an integer constant expression in the formal sense of the term.这取决于您希望如何分配它,但这是一种方法。
需要注意的是,当用于取消引用变量时,而不是在初始化期间,myPointer[i] 几乎与 *(myPointer + i) 完全相同。
Well it depends how you want it to be allocated, but here is one way.
something to note is that myPointer[i] is almost exactly identical to saying *(myPointer + i), when being used to dereference a variable, not during initialization.
试试这个:
Try this: