需要帮助。C++ Z:\动态分配.cpp(18):错误 C2440:'=':无法从 'int' 转换为 'int *'

Need help. C++ Z:Dynamic Allocation.cpp(18) : error C2440: '=' : cannot convert from 'int' to 'int *'

本文关键字:int 转换 C2440 C++ 帮助 动态分配 cpp 错误      更新时间:2023-10-16

//两个城镇之间的距离为380公里。一辆汽车和一辆卡车同时从两个城镇出发。如果汽车的速度比卡车的速度快5公里,并且我们知道他们在4小时后相遇,那么这两辆车的行驶速度是多少?使用动态内存分配和指针来计算和显示所需的信息。

// The distance between two towns is 380km. A car and a lorry started from the two towns at the same time. At what speed drove the two vehicles, if the speed of the car is with 5km faster than the speed of the lorry and we know that they met after 4 hours? Use Dynamic Memory Allocation and Pointer in calculating and Displaying the needed info.
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
int main ()
{
    int t=4;
    int d=380;
    int dt=20;
    int dd;
    int * ptr;
    int * ptr2;
    ptr  = (int*) malloc (500*sizeof(int));
    ptr2 = (int*) malloc (500*sizeof(int));
    dd=d-dt;
    ptr = dd/8;
    ptr2 = ptr+5;
    cout << " The Speed of the Car is: " << ptr << endl;
    cout << " The Speed of the Lorry is: " << ptr2 << endl;
    return(0);
}

我该怎么跑?如何在所有变量中使用动态内存分配?谢谢

要获得指针ptr指向的值,必须使用运算符*ptr 取消引用它

因此,更换

ptr = dd/8
ptr2 = ptr+5;

带有

*ptr = dd/8
*ptr2 = *ptr+5;

这个:

cout << " The Speed of the Car is: " << ptr << endl;
cout << " The Speed of the Lorry is: " << ptr2 << endl;

带有

cout << " The Speed of the Car is: " << *ptr << endl;
cout << " The Speed of the Lorry is: " << *ptr2 << endl

正如评论中的其他人已经指出的那样,您需要编写

*ptr = dd/8;
*ptr2 = ptr+5;

除此之外,您还需要free调用malloc获得的任何内存,但由于您正在尝试学习C++而不是C,我建议您改用newdelete

您还会发现(如果您的代码示例完整)缺少coutendlstd命名空间说明符