我必须拆分命令行参数才能确定文件类型。为了做到这一点,我使用
char fileName; //global variable, just below function prototypes
char *fileType;
fileType= strtok(inputFile, "."); //first string split
fileName= (int) &fileType; //store the file name for further use
fileType= strtok(NULL, "."); //get the file type
分词器功能正在工作,但为了将冗余代码保持在最低限度,我想存储文件名,因为稍后我必须创建一个具有相同名称但扩展名不同的新文件。
在调试器中,fileName 变量永远不会被使用。为什么?
最佳答案
关于
char fileName; //global variable, just below function prototypes
如果 fileName
应该是一个字符串,那么它必须是指向该字符串中第一个 char
的指针(即 char *fileName
)。
如果fileName
被认为是一个指向字符串的指针,那么它应该被声明为char **fileName
。
关于
char *fileType;
如果这是一个局部变量,并且fileName
是指向它的指针,那么函数返回后它将被销毁,并且指针将指向未知数据。
关于
fileName= (int) &fileType; //store the file name for further use
这对我来说似乎毫无意义。为什么要将 fileType
的地址转换为整数?我猜编译器会提示,因为 fileName
是 char
而不是 char *
并且您注意到这会修复错误。在不了解自己在做什么的情况下,不要进行此类修复,因为这样的编程只会导致深奥的代码,无论如何都可能无法按预期工作。
因此,如果 fileName
定义为 char *
,则只需执行 fileName = fileType
即可。否则,如果 fileName
声明为 char **
则执行 fileName = &fileType
;
关于
fileType= strtok(NULL, "."); //get the file type
如果strtok()
可以返回一个指向新字符串的指针,并且fileName
被声明为char *
,那么你之前存储在其中的任何内容都将不再有意义。在这种情况下,fileName
需要是一个 char **
(指向字符串的指针),这是我在第一条评论中提出的。
关于c - 如何将指针赋值给全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5068767/