如何在 C 中定义具有可变值的字符串数组
我想创建一个字符串数组,以便可以用要由 execv 执行的输入填充条目。这必须在运行时完成,使其像普通 shell 一样,但我检查过的有关此事的任何解决方案都会创建一个不可变数组,该数组无法在运行时获取所需的输入。那么c中字符串数组的表示法是什么?
I want to create an array of strings so i can fill the entries with inputs to be executed by execv. This has to be done during runtime, making it like a normal shell, but any solution i've checked regarding the matter creates an immutable array which can't take the required inputs during runtime. So what's the notation for an Array of strings in c?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的数组中,您将只有指向字符串的指针。对于实际的字符串(即:字符数组),您可以使用 malloc() 来保留内存。作为以空字符结尾的字符串,指针数组也以空指针结尾:
当然,您也可以使用 malloc 为指针数组保留内存,并且也严格只保留需要的内存对于各个字符串。
之后不要忘记释放内存。记忆值得自由!
In your array, you will have only pointers to strings. For the actual strings, (that is: character arrays) you use
malloc()
to reserve memory. And as a string terminated with a null character, the array of pointers is terminated by a null pointer:Of course you could reserve memory for the pointer array also with
malloc
, and also strictly reserve only what is needed for the individual strings.Don't forget to free memory afterwards. Memory deserves freedom!