为什么++没有正确递增?

2tr*_*ill -4 c pointers post-increment

我写了一个简单的函数来计算目录中非隐藏文件的数量.但是我注意到,当我++以前增加计数值时,我得到了奇怪的结果,比如负数和非常大的数字.当我切换*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;
}
Run Code Online (Sandbox Code Playgroud)

小智 6

*count++扩展到*(count++),(*count)++不像你期望的那样.您正在递增地址,而不是文件计数.