c++ - 在 C++ 中更改内存值

标签 c++

我对 C++ 编码比较陌生,并被要求创建一个处理指针和地址的程序。我遇到的问题是使用两个内存地址之间的差异来更改分子的值(我们正在处理分数)。

这是我分配的作业:http://cdn.frugalfinders.com/assignment.pdf

我陷入了问题 2。这是我到目前为止的 C++ 代码:

#include <iostream>
#include <fstream>
#include <cstring>
#include "fraction.h"
using namespace std;

int main()
{
    int i1;
    fraction f1(2,5);
    int i2;
    fraction farray[5];
    float x1;
    double x2;
    char c1;
    int A[6];
    int *ip1;
    float *fp1;
    fraction *ffp1;
    double *dp1;

    // Print the addresses of the variables
    cout << endl;
    cout << "i1 at:       " << &i1 << endl;
    cout << "f1 at:       " << &f1 << endl;
    cout << "i2 at:       " << &i2 << endl;
    cout << "farray at:   " << &farray << endl;
    cout << "x1 at:       " << &x1 << endl;
    cout << "x2 at:       " << &x2 << endl;
    cout << "c1 at:       " << &c1 << endl;
    cout << "A at:        " << &A << endl;
    cout << "ip1 at:      " << &ip1 << endl;
    cout << "fp1 at:      " << &fp1 << endl;
    cout << "ffp1 at:     " << &ffp1 << endl;
    cout << "dp1 at:      " << &dp1 << endl;

    // Print the values of the variables
    cout << endl;
    cout << "f1 is:       " << f1 << endl;
    cout << "ip1 is:      " << ip1 << endl;
    cout << "fp1 is:      " << fp1 << endl;
    cout << "ffp1 is:     " << ffp1 << endl;
    cout << "dp1 is:      " << dp1 << endl << endl;

    // Store the address of i2 in ip1
    ip1 = &i2;

    // Change the numerator of f1 to 23
    cout << f1 << endl;
    i1 = (&i2) - 4;
    *i1 = 23;
    cout << f1 << endl;

    return 0;
}

我只是不知道如何获得下面的部分

// Change the numerator of f1 to 23

去上类。非常感谢任何帮助!

最佳答案

我猜(实际上不可能肯定地说)你可能会得到你期望的输出

*(ip1 - 2) = 23;

但这个练习确实是垃圾。你的教授要求你编写在 C++ 中完全非法的代码,而且我认为这没有任何用处。

为了稍微解释一下原因,您可以使用指针算术从现有地址获取新地址。但指针运算仅在某些情况下合法,并且使用指针运算从一个变量的地址获取另一个变量的地址是不合法的。但这就是你被要求做的。

关于c++ - 在 C++ 中更改内存值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16242957/

相关文章:

c++ - 从 QLocalSocket 读取超过 2048 个字节

c++ - 如何根据参数的类型实例化不同的类?

c++ - 编译代码时出错

c++ - 使用模板插入函数丢失数字

c++ - 抛出类中定义的类的对象

c++ - 处理记录最后 1000 个事件的文件操作的最佳方法

c++ - C++ 异或链表

c++ - 对象的内存分配

C++如何等待在另一个线程上执行的方法然后主线程完成(VS2010)

c++ - "Garbled"在 VST 插件中使用 FFTW 的声音