无法增加取消引用的指针的值

标签 c pointers increment fopen dereference

我似乎对一个简单的程序有问题,该程序应该计算文件中的各种字符类型。即使文件根本不为空,它也总是打印零。我认为这与指针有关,可能是错误的。我还想知道在这种情况下是否需要初始化变量?

// fun.h

void count_char(FILE *f, unsigned *newl, unsigned *let, unsigned *num, unsigned *spec_char);

// main.c

#include <stdio.h>
#include "fun.h"

int main()
{
    unsigned newline = 0, number = 0, letter = 0, special_character = 0;
    char path[256];
    FILE *f_read;
    printf("Insert a file path: ");
    gets(path);
    f_read = fopen(path, "r");
    if(f_read == NULL)
    {
        perror("The following error occurred");
        return 1;
    }
    count_char(f_read, &newline, &number, &letter, &special_character);
    printf("File content:\n\tnewline - %u\n\tletters - %u\n\tnumbers - %u\n\tspecial characters - %u\n", newline, number, letter, special_character);
    return 0;
}

// fun.c

#include <stdio.h>
#include <ctype.h>

void count_char(FILE *f, unsigned *newl, unsigned *let, unsigned *num, unsigned *spec_char)
{
    char c;
    while((c = fgetc(f)) != EOF)
    {
        if(c == '\n')
            *newl++;
        else if(isalpha(c))
            *let++;
        else if(isdigit(c))
            *num++;
        else
            *spec_char++;
    }
    return;
}

最佳答案

当你做这样的事情时:*newl++;;发生的情况是,首先,指针递增(即使其指向下一个内存位置),然后根据运算符优先级取消引用。

如果您想取消引用它然后递增,则必须使用括号,如下所示:(*newl)++;

关于无法增加取消引用的指针的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14367305/

相关文章:

java - Hibernate union-subclass (table per concrete class) "increment"的映射生成器很慢?

c++ - 指向 C++ 中的结构的指针 - 从控制台读取?

c - *(字符**)的使用

c - 用于在 btrfs 中的文件和目录上设置时间戳的 API

c++ - 为什么没有发生堆栈溢出?

C将指针传递给函数,如何?

c++ - 从函数返回的错误信息

php - 字符串的增量行为 - PHP 复活节彩蛋?

javascript - 如何增加 jQuery 元素 ID

c - %zd 说明符是 C11 中的可选功能吗?