【发布时间】:2019-02-11 07:05:46
【问题描述】:
我在某人的代码中遇到了这个...我不知道它是否正确(因为即使它看起来不对,它也可以工作)。有人可以澄清这是否正确,为什么是这样,以及为什么它仍然有效?
简而言之,我们希望将所有参数(以命令行形式给出)串联存储在 1 个字符串中。
注意:每个字符串至少有 1 个字符。
片段:
int main(int argc, char **argv) {
// Declaring a pointer to a string
char *desintation_string;
// Allocating enough memory to store all arguments (given as command-line) concatenated
destination_string = malloc((argc) * sizeof(char)); /* <————— is this correct ? does
it indeed allocate
enough memory to fit
all the arguments
concatenated ? */
. . .
}
问题是:
这行“destination_string = malloc((argc) * sizeof(char));”是否为此分配了足够的内存?
有人能解释一下这是做什么的吗?因为我把它读为:它正在分配(argc * 1 字节)。然而,当您运行它并将参数复制到它时,它会起作用,有人可以解释一下吗?
【问题讨论】:
-
只要您收到的每个字符串都有一个字符!
-
@CinCout .. 这不分配(argc * 1 字节)...如何存储所有参数的所有字符就足够了?还是我的假设错了?
-
@Lion 它完全按照你的想法做。
-
代码错误。阅读how to debug small programs。也可以使用valgrind
-
好的,谢谢.. 所以这是错误的。只是必须确保。
标签: c string malloc command-line-arguments allocation