修改结构指针中的C字符串

Modifying C string within a structure pointer

本文关键字:字符串 结构 指针 修改      更新时间:2023-10-16

我有这样的代码:

typedef struct
{
  char mode;       //e = encrypt, d = decrypt
  char* infile;    //name of infile
  char* outfile;   //name of outfile
  char* password;  //password string
} cipher_t;
int check_files(cipher_t *data)
{
  char temp_path[] = "temp-XXXXX";
  if( /** infile == stdin *//)
  {
    mkstemp(temp_path);
    *data.infile = temp_path;
  }
  //do stuff and return
}

基本上,我要做的是检测用户是否想从stdin输入数据,如果是,请创建一个临时文件,在那里我可以做一些事情。

这里的问题是,当我如上所示设置内野路径时,数据在退出函数时不会被保留,因为它是一个局部变量。因此,当我退出函数时,临时文件路径会在结构中丢失。除了物理复制字符串之外,我还能做些什么来保留值吗?

data->infile = strdup(temp_path);

除了物理复制字符串之外,我还能做些什么来保留值吗?

您可以将其声明为static,这将使"字符串"在整个程序的活动时间内活动。

static char temp_path[] = "temp-XXXXX";

但请注意,temp_path只存在一次,因此由多个线程访问它可能会导致混淆。