无法增加已取消引用的指针的值 [英] Cannot increment the value of a dereferenced pointer

查看:116
本文介绍了无法增加已取消引用的指针的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I seem to have a problem with a simple program that is supposed to count various character types in a file. It always prints zeroes even though the file is not empty at all. I think it has something to do with pointers, could be wrong. I would also like to know if initializing variables is necessary in this case?

// 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++;;发生的情况是,首先,将指针递增(即使其指向下一个内存位置),然后根据运算符的优先级对其进行取消引用.

When you do something like this: *newl++;; what happens is that first, the pointer is incremented (i.e. make it point to the next memory location) and THEN it is dereferenced based on operator precedence.

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

If you want to dereference it and then increment, you have to use parentheses, like this: (*newl)++;

这篇关于无法增加已取消引用的指针的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆