通过引用将字符串数组传递给 C 函数
我很难通过引用将字符串数组传递给函数。
char* parameters[513];
这代表513个字符串吗?以下是我初始化第一个元素的方式:
parameters[0] = "something";
现在,我需要通过引用将“参数”传递给函数,以便该函数可以向其中添加更多字符串。函数头看起来如何以及如何在函数内使用此变量?
I am having a hard time passing an array of strings to a function by reference.
char* parameters[513];
Does this represent 513 strings? Here is how I initialized the first element:
parameters[0] = "something";
Now, I need to pass 'parameters' to a function by reference so that the function can add more strings to it. How would the function header look and how would I use this variable inside the function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你已经明白了。
在 C 中,当您将数组传递给函数时,编译器会将数组转换为指针。 (数组“衰减”为指针。)上面的“func”完全等同于:
由于传递了指向数组的指针,因此当您修改数组时,您正在修改原始数组而不是副本。
您可能想了解指针和数组在 C 中的工作原理。与大多数语言不同,在 C 中,指针(引用)和数组在许多方面的处理方式类似。数组有时会衰减为指针,但仅限于非常特定的情况。例如,这不起作用:
You've already got it.
In C, when you pass an array to a function, the compiler turns the array into a pointer. (The array "decays" into a pointer.) The "func" above is exactly equivalent to:
Since a pointer to the array is passed, when you modify the array, you are modifying the original array and not a copy.
You may want to read up on how pointers and arrays work in C. Unlike most languages, in C, pointers (references) and arrays are treated similarly in many ways. An array sometimes decays into a pointer, but only under very specific circumstances. For example, this does not work:
char*parameters[513];
是一个包含 513 个指向char
指针的数组。它相当于char *(parameters[513])
。指向该事物的指针的类型为
char *(*parameters)[513]
(相当于char *((*parameters)[513])
),因此你的函数可能看起来像:或者,如果你想要 C++ 参考:
char* parameters[513];
is an array of 513 pointers tochar
. It's equivalent tochar *(parameters[513])
.A pointer to that thing is of type
char *(*parameters)[513]
(which is equivalent tochar *((*parameters)[513])
), so your function could look like:Or, if you want a C++ reference: