c - 在 C 中,如何动态地将命令行参数添加到字符串数组?

标签 c command-line-arguments dynamic-arrays argv c-strings

目前我能看到它的唯一方法是循环遍历 argv 参数列表,获取最大的输入字符串并创建一个新的动态数组,该数组的最大大小指示每个元素的内存分配。

或者有更直接的方法吗?

最佳答案

如果您将main 的签名定义为

int main(int argc, char *argv[]);

然后,这里的 argv 是一个指向作为命令行参数传递的字符串的指针数组。引用 C99 标准部分 5.1.2.2.1 -

The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.

因此,您既可以直接修改argv元素指向的字符串,也可以复制这些字符串然后进行处理。

#include <stdlib.h>

int main(int argc, char *argv[]) {
    char *strlist[argc];
    int i = 0;
    while(i < argc) {
        strlist[i] = malloc(1 + strlen(argv[i]));
        if(strlist[i] == NULL) {
            printf("not enough memory to allocate\n");
            // handle it
        }
        strcpy(strlist[i], argv[i]);
        i++;
    }
    // process strlist
    // after you are done with it, free it
    for(i = 0; i < argc; i++) {
        free(strlist[i]);
        strlist[i] = NULL;
    }

    return 0;    
}

关于c - 在 C 中,如何动态地将命令行参数添加到字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22593438/

相关文章:

java - C 中的命令行参数导致段错误?

c - 访问 C 中动态分配的嵌套结构

excel - 将excel的新动态数组功能与VBA相结合

c - opendir:打开的文件太多

mysql - c 上的 const char 具有相同的变量但不同的值

Python argparse 允许组合标志

python - argparse - 每个操作不同的强制/可用参数

c - 检测5秒内鼠标是否移动的函数

C 和 OpenMP : pointer to shared read-only data slows down execution

excel - 计算动态数组/范围内的小计