'String undeclared (first use in this function) when I clearly defined it. What's the problem?

I'm currently writing a program that recursively traverses through directories to find a specified target. When I try to compile the code, I'm getting the error "dirString undeclared (first use in this function) even though I have defined it. My guess is that at some point the conditionals are skipped and dirString is still uninitialized. Here is what I have.

void find_file(char* dir_name, char* file_to_find) {
   DIR *dp = opendir(dir_name);
   struct dirent* dirp;

   while ((dirp = readdir(dp)) != NULL) {
       if (dirp->d_type == DT_DIR) {
           if(!strstr(dirp->d_name, ".")) {
               char dirString[PATH_MAX];
               strcpy(dirString, dir_name);
               strcat(dirString, "/");
               strcat(dirString, dirp->d_name);
               find_file(dirString, file_to_find);
           }
       }
       if (strcmp(dirp->d_name, file_to_find) == 0) {
           printf("%s\n", dirString);
       }
   }
   closedir(dp);

   return;
}


Solution 1:[1]

The variable dirString is defined inside of the inner if block. You try try to reference it outside of that block, at which point it's out of scope and its lifetime has ended.

You need to move the variable and the statements that populate it outside of the inner if block so that it's visible where you need it.

   while ((dirp = readdir(dp)) != NULL) {
       char dirString[PATH_MAX];
       strcpy(dirString, dir_name);
       strcat(dirString, "/");
       strcat(dirString, dirp->d_name);
       if (dirp->d_type == DT_DIR) {
           if(!strstr(dirp->d_name, ".")) {
               find_file(dirString, file_to_find);
           }
       }
       if (strcmp(dirp->d_name, file_to_find) == 0) {
           printf("%s\n", dirString);
       }
   }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dbush