C++带有指针参数的函数
C++ function with pointer argument
我正在编写一个C++程序,该程序将数据输出到文件,生成python脚本并调用pyplot
进行绘图。
但是,当我根据指针传递参数时,它可以正确编译,但不能运行。 它返回错误。 当我使用Xcode 调试模式并逐步执行它时,它会偶然给出正确的结果,但并非总是如此。 有时它还会返回错误。
我怀疑这可能是由某些内存分配问题引起的,但我无法确定问题到底是什么。
我的代码如下:
1( 主要
#include <iostream>
#include <stdlib.h>
#include <cmath>
#include "PyCPlot.h"
using namespace std;
double pi = 3.1415926;
int main(int argc, const char * argv[]) {
int nline = 100;
double * np_list = new double(nline);
double * pack_fraction_np = new double (nline);
for (int i=0; i<nline; i++){
np_list[i] = double(i)/double(nline)*2*pi;
pack_fraction_np[i] = cos(np_list[i]);
}
PyCPlot_data_fout("RandomPacking", nline, np_list, pack_fraction_np);
PyCPlot_pythonscript("RandomPacking", "Random Packing");
PyCPlot_pyplot("RandomPacking", "Random Packing");
return 0;
}
2( 头文件
#ifndef PyCPlot_h
#define PyCPlot_h
#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int PyCPlot_data_fout(string datafilename, int nline, double * x, double *y){
ofstream fout;
fout.open(datafilename+".txt");
fout << nline << endl;
for (int i=0; i<nline; i++){
fout << x[i] << " " << y[i] << endl;
}
fout.close();
return 0;
}
int PyCPlot_pythonscript(string datafilename, string plttitle){
string strhead = "import numpy as npnimport matplotlib.pyplot as pltn";
string strpltfig = "plt.figure()n";
string strpltplt = "plt.plot(xlist, ylist)n";
string strplttit = "plt.title('"+plttitle+"')n";
string strpltshw = "plt.show()n";
string strfileopen ="f = open('"+datafilename+".txt', 'r')n";
string strreadline ="size = map(int, f.readline().split())n";
string strpltlist ="xlist = np.zeros((size))nylist = np.zeros((size))n";
string strfor = "for i in range(size[0]):n xlist[i], ylist[i] = map(float, f.readline().split())n";
ofstream pyout;
pyout.open("PyCPlot_"+datafilename+".py");
pyout << strhead << strfileopen << strreadline << strpltlist << strfor;
pyout << strpltfig << strpltplt << strplttit << strpltshw;
pyout.close();
return 0;
}
int PyCPlot_pyplot(string datafilename, string plttitle){
string strsystemsh ="source ~/.bashrc; python PyCPlot_"+datafilename+".py";
system(strsystemsh.c_str());
return 0;
}
#endif /* PyCPlot_h */
当它运行时,我收到以下错误消息
malloc: *** error for object 0x1002002e8: incorrect checksum for freed object - object was probably modified after being freed.
你想传递一个数组,所以传递一个可以在运行时调整大小的实际数组(std::vector
(,而不是一些希望指向数组的第一个元素的随机指针(在这种情况下,它没有(
你的错误是使用new double(x)
而不是new double[x]
。前者分配一个值等于x
的单个double
,后者分配大小x
的double
数组并返回指向第一个元素的指针,但是,正如我所说,如果您实际使用std::vector
并且没有像 90 年代初那样涉足指针,您根本不会遇到这个问题(更不用说, 如果您使用std::vector
(,您就不会有内存泄漏。
你正在做一些不对或看起来很奇怪的事情。
代码new double(nline)
将分配一个值为nline
的单精度值,这似乎不是您想要的。 看起来您打算动态分配一个双精度数组。实际上,从您展示的代码来看,您没有理由不能做一个简单的数组,因为大小在编译时是已知的。
下面的代码:
double * np_list = new double(nline);
double * pack_fraction_np = new double (nline);
可以替换为:
double np_list[nline];
double pack_fraction_np[nline];
以下行为np_list
和pack_fraction_np
分配一个双精度:
double * np_list = new double(nline);
double * pack_fraction_np = new double (nline);
因此,当您进入循环时,会将数据写入无效的内存块。你必须使用方括号来定义一个数组(我没有收到任何错误;使用 clang++(。
考虑使用std::vector
类。下面是一个示例(您的示例(,其中std::pair
double
嵌套在std::vector
中:
PyCPlot.h
#ifndef PyCPlot_h
#define PyCPlot_h
#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <vector>
#include <utility>
using namespace std;
int PyCPlot_data_fout(string datafilename, std::vector<std::pair<double, double>>& v){
ofstream fout;
fout.open(datafilename+".txt");
fout << v.size() << endl;
for (int i=0; i < v.size(); i++){
fout << v[i].first << " " << v[i].second << endl;
}
fout.close();
return 0;
}
int PyCPlot_pythonscript(string datafilename, string plttitle){
string strhead = "import numpy as npnimport matplotlib.pyplot as pltn";
string strpltfig = "plt.figure()n";
string strpltplt = "plt.plot(xlist, ylist)n";
string strplttit = "plt.title('"+plttitle+"')n";
string strpltshw = "plt.show()n";
string strfileopen ="f = open('"+datafilename+".txt', 'r')n";
string strreadline ="size = map(int, f.readline().split())n";
string strpltlist ="xlist = np.zeros((size))nylist = np.zeros((size))n";
string strfor = "for i in range(size[0]):n xlist[i], ylist[i] = map(float, f.readline().split())n";
ofstream pyout;
pyout.open("PyCPlot_"+datafilename+".py");
pyout << strhead << strfileopen << strreadline << strpltlist << strfor;
pyout << strpltfig << strpltplt << strplttit << strpltshw;
pyout.close();
return 0;
}
int PyCPlot_pyplot(string datafilename, string plttitle){
string strsystemsh ="source ~/.bashrc; python PyCPlot_"+datafilename+".py";
system(strsystemsh.c_str());
return 0;
}
#endif /* PyCPlot_h */
PyCPlot.cpp
#include <iostream>
#include <stdlib.h>
#include <cmath>
#include "PyCPlot.h"
using namespace std;
double pi = 3.1415926;
int main(int argc, const char * argv[]) {
int nline = 100;
std::vector<std::pair<double, double>> v;
v.reserve(nline);
double a;
for (int i=0; i < nline; i++){
a = double(i)/double(nline)*2*pi;
v.push_back(std::make_pair(a, cos(a)));
}
PyCPlot_data_fout("RandomPacking", v);
PyCPlot_pythonscript("RandomPacking", "Random Packing");
PyCPlot_pyplot("RandomPacking", "Random Packing");
return 0;
}
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数