对 char 和 char * 感到困惑,并在单词中扫描

标签 c if-statement char int scanf

我写了这个简单的代码来扫描一些数字和单词。但是,我很困惑,因为 char 总是给我一个错误。有什么问题吗?

int main(int argc, char *argv[]) {
    int val_pos, incr_val, max_val;
    char *file_name;
    char *new_name;

    if (argc == 6) {

        val_pos = atoi(argv[1]);
        incr_val = atoi(argv[2]);
        max_val = atoi(argv[3]);
        file_name = argv[4];
        new_name = argv[5];

    } else {

        printf("Command usage: %s <val_pos> <increment val> <max val> <file_name> <new name>\n", argv[0]);

        printf("What is the position you want to change? Enter your number\n");
        printf("X = 0 | Y = 1 | Z = 2\n");
        scanf("%d", &val_pos);

        printf("What is the increment value?\n");
        scanf("%d", &incr_val);

        printf("What is the max value/value we should terminate at?\n");
        scanf("%d", &max_val);

        printf("What is the pose file called?\n");
        scanf("%s", &file_name);

        printf("What should we call the newly generated files?\n");
        scanf("%s", &new_name);
    }
}

最佳答案

这里

char *file_name;
char *new_name;

file_namenew_name 是字符指针,它们没有被初始化,所以它们没有指向任何有效的内存位置;如果你喜欢

scanf("%s", &file_name);
scanf("%s", &new_name);

它会导致段错误,因为您没有为 file_namenew_name 分配任何内存。

正确的做法是先为file_namenew_name分配内存,然后扫描数据

char *file_name = malloc(F_SIZE); /* define F_SIZE */
char *new_name = malloc(N_SIZE); /* define the N_SIZE as how much size you want */

现在像这样扫描数据

scanf("%s",file_name); /* & is not required */
scanf("%s",new_name);

完成file_namenew_name 后,不要忘记调用free() 释放动态内存以避免内存泄漏,例如

free(file_name);
free(new_name);

旁注:您的编译器可能会警告您

scanf("%s", &file_name); /* & is not needed */

喜欢

format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’

还有关于

char *file_name; /* uninitialized */

‘file_name’ may be used uninitialized in this function

如果您使用适当的标志编译您的代码。我建议你用

编译任何基本的 C 代码
gcc -Wall -Wstrict-prototypes -Werror test.c

它对您有很大帮助,因为有时人们过去常常从字面上接受警告,但后来它们的成本更高。因此,最好通过使用 -Werror 编译将警告转换为错误并继续。

关于对 char 和 char * 感到困惑,并在单词中扫描,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50885659/

相关文章:

c++ - 删除一个 char* 崩溃程序

c - 为什么我在 C 中使用 strtok 时不断收到编译器错误?

c - 生成原始比特流作为输出以在另一个软件中进行管道传输

输入后忽略回车键的C代码

C if 语句将两个整数变量与同一个常量进行比较

python - 简化 if 语句 Python

c - TCP套接字到多个IP/端口

if-statement - 根据所选选项增加 2 个不同的 ID

c - 如何将 tolower() 与 char* 一起使用?

c++ - 在 C++ 中,所有键都可以表示为单个字符吗?