0

// 两个城镇之间的距离是 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);
}

我怎样才能让这个运行?如何在所有变量中使用动态内存分配?谢谢。

4

2 回答 2

1

要获取指针指向的值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

;

于 2013-08-30T07:39:12.587 回答
0

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

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

除此之外,您还需要free通过调用获得的任何内存malloc,但是当您尝试学习 C++ 而不是 C 时,我建议使用newanddelete来代替。

您还会发现(如果您的代码示例完整)您std缺少coutendl

于 2013-08-30T07:51:15.233 回答