【发布时间】:2019-08-19 05:54:15
【问题描述】:
我正在编写一个接受命令行参数的程序,我想使用字符串“PIPE”分隔所有参数,例如我可以编写 ls -la PIPE wc。 我的代码
char **args = argv;
int pipes=0;
while(*args)
{
if(strcmp("PIPE",*args) == 0)
{
pipes++;
}
args++;
}
int *pipeIndexes = NULL;
if(pipes > 0)
{
pipeIndexes=(int *)malloc(pipes*sizeof(int));
args = argv;
pipeIndexes[pipes];
int counter=0,i=0;
while(*args)
{
if(strcmp("PIPE",*args) == 0)
{
pipeIndexes = (int *)realloc(pipeIndexes,sizeof(int)*(counter+1));
pipeIndexes[counter] = i;
counter++;
}
i++;
args++;
}
}
现在我想做的是创建另一个数组来存储每个程序的参数?例如。
programs = { {"ls","-la"},{"wc"}}
【问题讨论】:
-
我给出了一个建议和执行示例的答案,我在每个构建(子)数组的末尾添加了 NULL 来标记它们的末尾,就像 argv 末尾有一个 NULL 一样跨度>
-
@bruno 谢谢我想我忘了标记是一个解决方案。我有一个问题,为什么要为 n+2 分配内存?我知道 +1 最后是 NULL 但为什么 + 2?
-
是 n+2,因为 +1 表示新元素,+1 表示最后添加的 NULL(n 在 malloc 之后 递增)
标签: c malloc realloc jagged-arrays