C - char*为空?

Jor*_*dan 1 c

这可能很简单,但我无法弄清楚为什么我无法从这个char*中获取值.

这是我的问题:

static char* DIR_ENTRY_PATH = NULL;
Run Code Online (Sandbox Code Playgroud)

...

while (1) // infinite loop

    {

      // accept a client connection 

      clientFd = accept (serverFd, clientSockAddrPtr, &clientLen);

      if (fork() == 0) // Create child proc to get dir entry info 

        {

          //read dir entry info     
readInfo(clientFd);
printf("dpath: %s\n", DIR_ENTRY_PATH); //prints out the the correct value (DIR_ENTRY_PATH set in readInfo)
int test = 1;
      //get dir entry info and write back
      DIR *dir;
      struct dirent *entry; //pointer to dir entry
      struct stat stbuf; //contains file info

      if((dir = opendir(DIR_ENTRY_PATH)) == NULL){ //make sure entry is valid
        printf("error with dirent\n");
            exit(1);
      }
      else{
        printf("gathering directory entry info...\n");
        while((entry = readdir(dir)) != NULL){
            char *entryname = entry->d_name;
printf("path: %s\n", DIR_ENTRY_PATH); /*prints nothing out.. */ - PROBLEM IS HERE
printf("int: %d\n", test); //*prints 1 out.. */
Run Code Online (Sandbox Code Playgroud)

...

readInfo():

//reads info from the client
void readInfo(int fdesc){
  int fd = fdesc;
  char str[200];

  readLine(fd, str); //read line in from socket
  DIR_ENTRY_PATH = str; 
  printf("received path: %s\n", DIR_ENTRY_PATH); //displays correct value
}
//reads a single line
int readLine(int fdesc, char *strng){
 int fd = fdesc;
 char *str = strng;
 int n;

 do{
   n = read(fd,str, 1); //read a single character
 }while(n > 0 && *str++ != 0);
 return (n>0); //return false if eoi
}//end readLine
Run Code Online (Sandbox Code Playgroud)

为什么我能够获得测试int的值而不是dir_entry_path?谢谢你的帮助.

Jon*_*ler 6

您正在为全局变量分配一个指向局部变量的指针,但是一旦函数返回,局部变量就会消失!

void readInfo(int fdesc){
  int fd = fdesc;
  char str[200];             // Local variable

  readLine(fd, str);
  DIR_ENTRY_PATH = str;      // Pointer assigned to global
  printf("received path: %s\n", DIR_ENTRY_PATH); //displays correct value
}
Run Code Online (Sandbox Code Playgroud)

函数返回后,局部变量未定义,其存储可以被下一个函数等重用.

如何解决问题?有许多可能的方法,但最简单的方法可能是:

static char DIR_ENTRY_PATH[1024];

void readInfo(int fdesc){
  int fd = fdesc;
  char str[200];                  // Local variable

  readLine(fd, str);
  strcpy(DIR_ENTRY_PATH, str);    // Copy local string into global string

  printf("received path: %s\n", DIR_ENTRY_PATH); //displays correct value
}
Run Code Online (Sandbox Code Playgroud)

作为一个风格点,ALL_CAPS通常表示一个宏或一个enum值(因为enum有点像#define使用ALL_CAPS).

我希望你有适当的界限检查readLine().我对我的修改很懒惰,只是确保全局比局部变量长(五倍).调整适合自己.我还使用了一个enum缓冲区大小(而不是小写名称DIR_ENTRY_PATH).