问题描述
我正在使用Visual Studio 2005(C \ C ++).
I am using Visual Studio 2005 (C\C++).
我正在将字符串作为char数组传递给函数.我想打开作为参数传入的文件并使用它.我知道我的代码在一定程度上可以正常工作,因为如果我将文件名硬编码为第一个参数,那么它就可以正常工作.
I am passing a string into a function as a char array. I want to open the file passed in as a parameter and use it. I know my code works to an extent, because if I hardcode the filename as the first parameter it works perfectly.
我确实注意到,如果我将值视为手表,则该值包括除字符串文字之外的地址.我尝试将文件名作为指针传递,但随后它抱怨使用__w64进行类型转换.就像我之前说过的,它可以用"filename.txt"代替fileName正常工作.我感到难过.
I do notice if I look at the value as a watch, the value includes the address aside the string literal. I have tried passing in the filename as a pointer, but it then complains about type conversion with __w64. As I said before it works fine with "filename.txt" in place of fileName. I am stumped.
void read(char fileName[50],int destArray[MAX_R][MAX_C],int demSize[2])
{
int rows=0;
int cols=0;
int row=0;
int col=0;
FILE * f = fopen(fileName,"r");
...
调用函数代码为:
char in_filename[50];
int dem[MAX_R][MAX_C];
int dem_size[2];
get_user_input( in_filename);
read(in_filename, dem, dem_size );
在我为文件名添加的手表中,出现了正确的文本,因此数据正在传入.
In the watch I added for filename the correct text appears, so the data is getting passed in.
推荐答案
如果您使用的是fopen()
,则说明是使用C而不是C ++进行编码.同样,这也不是将数组传递给函数的方式.参数列表的语法为
If you're using fopen()
then you're coding in C, not C++. Also, this is not how you pass arrays to functions. The syntax for the parameter list is
void f(char arr[], unsigned int arr_size);
对于多维数组,您必须明确指定最右边维的大小:
In the case of multidimensional arrays you must specify the size of the right-most dimension explicitly:
void f(char arr[][20], unsigned int arr_size);
也就是说,尝试将参数从char fileName[50]
更改为char* fileName
.
That said, try changing the parameter from char fileName[50]
to char* fileName
.
这篇关于C-使用fopen在函数内部打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!