2015-09-11 79 views
-4

我写了一个简单的函数来计算目录中非隐藏文件的数量。但是我注意到当我使用++增加计数值时,我得到了奇怪的结果,如负数和非常大的数字。当我将行*count++;切换为*count = *count + 1;时,该函数的行为与我的预期相同。有人可以解释这种行为吗?++为什么不能正确增加?

要使用此示例程序将路径作为第一个参数传递给目录。

#include <stdio.h> 
#include <dirent.h> 

int count_files_directory(unsigned int *count, char *dir_path) 
{ 
    struct dirent *entry; 
    DIR *directory; 

    /* Open the directory. */ 
    directory = opendir(dir_path); 
    if(directory == NULL) 
    { 
     perror("opendir:"); 
     return -1; 
    } 

    /* Walk the directory. */ 
    while((entry = readdir(directory)) != NULL) 
    { 
     /* Skip hidden files. */ 
     if(entry->d_name[0] == '.') 
     { 
      continue; 
     } 

     printf("count: %d\n", *count); 

     /* Increment the file count. */ 
     *count++; 
    } 

    /* Close the directory. */ 
    closedir(directory); 

    return 0; 
} 

int main(int argc, char *argv[]) 
{ 
    int rtrn; 
    unsigned int count = 0; 

    rtrn = count_files_directory(&count, argv[1]); 
    if(rtrn < 0) 
    { 
     printf("Can't count files\n"); 
     return -1; 
    } 

    return 0; 
} 
+0

Downvoter心灵解释? – 2trill2spill

+1

我觉得'* count ++'意思是'*(count ++)'(增加指针),但是你希望'(* count)++'(增加指向的值) – ikegami

+1

看看运算符的优先级 – 7VoltCrayon

回答

4

我相信,按照该operator precedence

*count++; 

应该被写成

(*count)++; 

否则,您遇到的确切相反(或者,对于问题,无效)行动比你所期望的。

6

*count++扩大到*(count++),而不是(*count)++像你所期待的。您正在增加地址,而不是文件数量。

0

您正在增加指针而不是变量。你需要尊重指针(count)。 更好和更干净的解决方案是简单地返回文件数量而不是传递参数。 这消除了任何需要一个指针来保持计数,并使方法签名更易于使用。

int count_files_directory(char *dir_path) 
{ 
    int noOfFiles = 0; 
    // Count files (omitted here) 

    return noOfFiles; 
} 
0

假设你数为10的值,并存储在存储位置100。当你做这样的事情

*count++ 

你现在指向的内存位置101.你想做的事是什么更改内存位置100的值不会去到内存位置101.因此,您首先要解除引用它,然后增加存储在那里的所有内容。

(*count)++; 

当你

*count = *count + 1; 

你去参考,然后递增,随后将其存储回内存位置值100