c - C 中的指针和动态内存分配

标签 c malloc args

我对 C 语言相当陌生,对指针和动态内存分配有点困惑。我想做的是读取命令行参数并将它们存储在动态内存分配中;然后打印出来。例如,如果我输入 ./rpd 4 3 2 3 8,则 argv[1] (4) 应递减,其他 3 个值 (3, 2, 3, 8) 应随之递减。输出应如下所示:

第 1 个人有 3 辆车。 2 个人有 2 辆车。 3 人有 3 辆车。 4 人有 8 辆车。

我的代码是:

  #include <stdio.h>

int main(int argc, char *argv[]) {
    /** argc is number of arguments at command line*/
    /** argv[] is an array of pointers to character strings
        i.e. argv 1 points to argc 1 */
    int numberOfCars;
    char *person;
    int i;
    int j;

    // Allocate the size of the array for each element of char
    person = malloc(sizeof(numberOfCars) *argc);

    for(i = 2; i < argc; i++) {
        /** Convert char to int */
        numberOfCars = atoi(argv[i]);
        person = atoi(argv[1]);
        if(person > 0){
            for(j = 2; j < person; j--) {
                printf("Person %d has %d cars \n", person--, numberOfCars);
            }
        } else {
            /** DO NOTHING */
        }
    }
    return person;
}

如果这让我有点困惑(或天真),我很抱歉;但我对这门语言非常陌生,所以我仍在努力理解一切。

非常感谢您的帮助:)

最佳答案

尝试这样的事情:

#include <stdio.h>

int main(int argc, char *argv[]) {
    /** argc is number of arguments at command line*/
    /** argv[] is an array of pointers to character strings
        i.e. argv 1 points to argc 1 */
    int numberOfCars;
    int i;

    for(i = 1; i < argc; i++) {
        /** Convert char to int */
        numberOfCars = atoi(argv[i]);
        printf("Person %d has %d cars \n", i, numberOfCars);
    }

    return 0;
}

然后根据您的需要进行调整。您不需要为第一个输入参数指定人数,因为您为每个人指定的汽车数量暗示了这一点。

关于c - C 中的指针和动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19892766/

相关文章:

c - Linux - 从 malloc 复制虚拟内存地址或移动虚拟内存地址

使用 C/C++ 创建 "invisible"windows 程序

c - 这些链接器的行为是什么?

C、内联函数和GCC

c - 为什么这个 C 程序不会崩溃?

c - 将数字从文件传递到结构中

python - 如何在函数中使用 *args 返回字典列表?

python - 比较 Python 中可变数量的非关键字参数

java - Maven exec 插件-硬编码参数后来自控制台的用户参数

在 Mac 终端中编译并运行 Sublime Text 文件