我写了这个简单的代码来扫描一些数字和单词。但是,我很困惑,因为 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_name
和 new_name
是字符指针,它们没有被初始化,所以它们没有指向任何有效的内存位置;如果你喜欢
scanf("%s", &file_name);
scanf("%s", &new_name);
它会导致段错误,因为您没有为 file_name
和 new_name
分配任何内存。
正确的做法是先为file_name
和new_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_name
和new_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/