我有一个关于将一个char数组变量从一个函数传递到下一个函数的问题。
以下是所涉及的代码示例:
int main( int argc, char** argv )
{
int value = 0;
int nCounter = 0;
FILE* fIn = NULL;
char * sLine = new char[MAX_FILENAME_SIZE];
char * sFileName = new char [MAX_FILENAME_SIZE];
char * s = new char [MAX_FILENAME_SIZE];
if ((fIn = fopen(ImgListFileName,"rt"))==NULL)
{
printf("Failed to open file: %sn",ImgListFileName);
return nCounter;
}
while(!feof(fIn)){
//set the variables to 0
memset(sLine,0,MAX_FILENAME_SIZE*sizeof(char));
memset(sFileName,0,MAX_FILENAME_SIZE*sizeof(char));
memset(s,0,MAX_FILENAME_SIZE*sizeof(char));
//read one line (one image filename)
//sLine will contain one line from the text file
fgets(sLine,MAX_FILENAME_SIZE,fIn);
//copy the filename into variable s
strncpy(s, sLine, strlen(sLine)-1);
//put a character at the end of the filename
strcat(sLine," ");
//create the filename
strcat(sFileName,s);
nCounter++;
fclose(fIn);
delete sLine;
delete sFileName;
delete s;
const int size = 60;
char path[size] = "path";
strcat(path,sFileName);
printf (path);
IplImage *img = cvLoadImage(path);
detect_and_draw(img);
cvWaitKey();
cvReleaseImage(&img);
cvDestroyWindow("result");
void detect_and_draw( IplImage* img )
{
More code that isn't involved....
cvSaveImage(sFileName, img);
现在,我尝试了以下方法:
void getFilename(char * sFileName)
{
printf("The filename is %sn", sFileName);
return;
}
然后用打电话
char * S ="string"
getFilename(S);
cvSaveImage(S,img);
但是"字符串"被放在"文件名是:字符串"中。
我该怎么做才能在cvSaveImage(sFileName,img)中使用sFileName(char数组)?
提前感谢,如果您需要任何进一步的澄清,请询问!
忽略未定义的行为、不必要的动态分配等,您似乎试图完成的事情可以归结为以下一般顺序:
std::string path;
while (std::getline(fIn, path)) {
std::cout << "path: " << path;
IplImage *img = cvLoadImage(path.c_str());
detect_and_draw(img, path);
cvWaitKey();
cvReleaseImage(&img);
cvDestroyWindow("result");
}
void detect_and_draw(IpImage *img, std::string const &path) {
// ...
cvSaveImage(path.c_str(), img);
}
不过,我想我会做一些不同的事情——可能从Image
类开始,比如:
class Image {
IpImage *img;
std::string path;
public:
Image(std::string const &name) :
img(cvLoadImage(name.c_str()), path(name)
{ }
~Image() { cvReleaseImage(&img); }
void detect_and_draw() {
// ...
cvSaveImage(path);
}
};
使用它,您的代码看起来更像这样:
while (std::getline(fIn, path)) {
Image img(path);
img.detect_and_draw();
cvWaitKey();
cvDestroyWindow("result");
}
这还不完全清楚,但cvDestroyWindow
听起来也很像是真正属于析构函数的东西,但我对这些部分如何组合在一起还不够确定是什么析构函数——也许Image
,更可能是其他东西。
我要注意的是,detect_and_draw
实际上尖叫着"这个代码忽略了单一责任原则"。它在名称中列出了两个职责,并且似乎至少有第三个职责(保存文件)。
如果我理解正确,那么您所面临的是范围界定问题。你基本上有:
int main(/* */)
{ char sFileName[MAX_FILENAME_SIZE];
/* code to initialize sFileName to contain a value */
detect_and_draw(img);
}
void detect_and_draw(IplImage *img)
{ cvSaveImage(sFileName, img);
}
问题是sFileName
对于main()
是本地的,并且在detect_and_draw()
中不可访问。您可以修改detect_and_draw()
以采用第二个参数:
int main()
{ /* stuff */
detect_and_draw(img, sFileName);
}
void detect_and_draw(IplImage *img, const char* fn)
{ cvSaveImage(fn, img);
}
或者使sFileName成为在main()
范围之外声明/定义的全局变量——尽管这通常被认为是一个较差的解决方案。