我想读取三个文件的路径(例如"../c/..file"),以及来自argv []的long并将它们绑定到三个已经创建的char*,并且还要调用一个long值NUM.
这是我的主要功能:
int main(int argc, char* argv[]){
char* file1 = NULL;
char* file2 = NULL;
char* file3 = NULL;
long num = 0;
//copy the file paths to the char*'s
strcpy(file1, argv[1]);
strcpy(file2, argv[2]);
strcpy(file3, argv[3]);
// convert from string to long int
num = strtol(argv[4],NULL,0);
}
Run Code Online (Sandbox Code Playgroud)
但是这不起作用,文件的文件名和long的值不会像它们应该的那样最终变量.
我怎样才能解决这个问题 ?
在我的程序中,我检查argc值,以确保我没有传递错误的东西,但在这里我写这个函数只是为了说明我的问题.
不要strcpy指向未指向已分配内存的指针.相反,只需将它们设置为等于argv数组中的指针,这些指针已指向已分配的内存.像这样:
int main(int argc, char *argv[])
{
if (argc < 5)
fprintf(stderr, "usage: %s <file1> <file2> <file3> <num>\n", argv[0]), exit(1);
char *file1 = argv[1];
char *file2 = argv[2];
char *file3 = argv[3];
long num = strtol(argv[4], NULL, 0);
/* Do stuff */
return 0;
}
Run Code Online (Sandbox Code Playgroud)