需要帮助。C++ Z:\动态分配.cpp(18):错误 C2440:'=':无法从 'int' 转换为 'int *'
Need help. C++ Z:Dynamic Allocation.cpp(18) : error C2440: '=' : cannot convert from 'int' to 'int *'
//两个城镇之间的距离为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,我建议您改用new
和delete
。
您还会发现(如果您的代码示例完整)缺少cout
和endl
的std
命名空间说明符
相关文章:
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 将字符串中的 int 转换为字母;
- 主.cpp:18:20:错误:从"int*"转换为"int"会失去精度 [-fa
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- 如何将矢量<int>转换为字符数组?
- C++ 无法从 const int* 转换为 const_iterator
- 我不断收到错误 C2440'=':无法从"int *(__cdecl *)(int *,int *,int,int)"转换为"int *
- 如何将 int[4] 转换为 std::array<int,4>?
- 如何将data[i].int转换为vaible
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将私有矩阵形式 int 转换为双 C++
- 无法将参数 1 从 'int' 转换为 'int &'
- 将 int 转换为字符串后始终得到 0
- isspace 函数的性能警告,从 int 转换为布尔值
- 将大 int 转换为浮点数,而不舍入 c++
- 错误:无法将'uint8* {aka unsigned int*}'转换为"常量emxArray_uint8_T*"?
- 将未签名的INT转换为BCD
- 在 C++ 中将 int 转换为双精度