c - 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);
}
解决方案
您必须取消引用指针才能更改它指向的值。但我认为年龄变量根本不应该是一个指针。它应该是int
:
typedef struct {
int age;
const char* name;
} Person;
30
这解决了您的许多问题,包括您强制转换为指针并用于打印指针的事实%d
,这会导致未定义的行为。
推荐阅读
- javascript - JS - 将 div 的所有子元素包装在一个包装器 div 中
- installation - 具有多个版本和安装目录的 inno 设置复选框
- actions-on-google - 如何使用 Diagflow 识别唯一用户
- ethereum - 使用 Web3js 发送 erc20 令牌
- ruby-on-rails - Stripe Subscription - 服务器以状态 400 响应
- vba - 如何在visual basic中随机打乱图片
- encryption - 只有一个人拥有公钥/私钥时的数字签名
- javascript - 为什么 JavaScript 函数不起作用?
- octave - 非线性拟合 Octave
- java - 为什么 ActionListener 不工作?