首页 > 解决方案 > C中的增量问题(指针)

问题描述

我只能更改“生日”功能的内容,其余的必须保持不变。

我在尝试增加年龄变量时遇到了一个愚蠢的问题......如果我使用 ++ 运算符而不是十进制 1,它确实会增加,它似乎增加了 4,这是一个 int 的大小。我在这里做错了什么?

    #include <stdio.h>

typedef struct {
    int* age;
    const char* name;
} Person;

void birthday(Person* person);


int main()
{
    void(*birthday_ptr)(Person* person) = &birthday;
    Person me = {30,"foobar"};
    (*birthday_ptr)(&me);
    return 0;
    }

void birthday(Person* person)
{
    printf("%p\n", person);
    printf("%d\n", person->age);
    person->age = 31; // this works...it sets the value pointed to by the ptr to 31...
    printf("%d\n", person->age);
    person->age += 1; // this compiles, but it seems to increment by 4 the value pointed to by the ptr, not 1 (relates to int size ?!)
    printf("%d\n", person->age);
    int* silly = (int*)(person);
    (*silly)++; // this works and increments age to 36...
    (*person->age)++; // this causes an access violation...why ?! 
    printf("silly: %d\n", person->age);
}

标签: cpointers

解决方案


您必须取消引用指针才能更改它指向的值。但我认为年龄变量根本不应该是一个指针。它应该是int

typedef struct {
    int age;
    const char* name;
} Person;

30这解决了您的许多问题,包括您强制转换为指针并用于打印指针的事实%d,这会导致未定义的行为。


推荐阅读