2013-08-30 73 views
0

//两个城镇之间的距离为380km。一辆汽车和一辆卡车同时从两个城镇出发。两辆车以何种速度驾驶,如果汽车的速度比货车的速度快5公里,并且我们知道他们在4小时后会见了?使用动态内存分配和指针计算和显示所需的信息。需要帮助。 C++ Z: Dynamic Allocation.cpp(18):error C2440:'=':无法从'int'转换为'int *'

// 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

本声明:'PTR = DD/8;'是错误的。你将一个整数除法的结果赋给一个指针变量,并且在这个过程中增加了对受伤的伤害和内存泄漏。你同样会泄漏先前分配给下一行'ptr2'的内存。 – WhozCraig

+0

你可能打算使用'* ptr'和'* ptr2'(假设你想修改它们指向的值)。 – SingerOfTheFall

+0

我是C++新手,你能帮助我吗? – StackingErrors

回答

1

要必须取消对它的引用使用运算*ptr

这样一个指针获得价值ptr点给你,更换

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 

;

0

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

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

除此之外,你还需要free通过调用malloc有任何记忆,但是当你正在努力学习C++而不是C,我推荐使用newdelete

你还会发现(如果你的代码示例是完整的),你是缺少coutstd命名空间符和endl

相关问题