如何指定全局变量的指针?

时间:2011-02-21 16:52:46

标签: c string global-variables

我必须拆分命令行参数以确定文件类型。为了做到这一点,我正在使用

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变量。为什么呢?

2 个答案:

答案 0 :(得分:1)

关于

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的地址转换为整数?我想编译器抱怨,因为fileNamechar而不是char *,你注意到这会修复错误。如果不了解你正在做的事情,不要做这种修复,因为这样的编程只会产生深奥的代码,而这些代码可能无论如何都不会按预期工作。

因此,如果将fileName定义为char *,那么只需执行fileName = fileType。否则,如果fileName被声明为char **,则执行fileName = &fileType;


关于

fileType= strtok(NULL, "."); //get the file type

如果strtok()可以返回指向 new 字符串的指针,并且fileName被声明为char *,那么之前存储在其中的任何内容都不会再有意义了。在这种情况下,fileName需要是我在第一条评论中提出的char **(指向字符串的指针)。

答案 1 :(得分:0)

您需要使用char数组和strcpy

像这样:

#define MAX_FILENAME_SIZE 200
char fileName[MAX_FILENAME_SIZE];

int f()
{
    fileType = strtok(inputFule, ".");
    // then use strcpy
    strcpy(fileName, fileType);

}

char全局只会存储一个字符。

相关问题