[英]cannot fscanf into a double dereferenced pointer
I have an array elsewhere in my program: 我在程序的其他地方有一个数组:
data=malloc(sizeof(int)*lines);
I want to read data from a file into this array. 我想将文件中的数据读取到此数组中。 I have opened the file etc.
我已打开文件等。
I created a function to read the data into this array: 我创建了一个函数来将数据读取到此数组中:
int readfile(FILE* fp,int** storage_array,int lines)
{
int i=0;
for(i=0; i<lines; i++)
{
fscanf(fp,"%lf",&(**storage_array+i));
}
rewind(fp);
return 0;
}
Dev c++ gives me 开发C ++给我
invalid lvalue in unary '&'
I have tried so many different ways to get this to work and it's really stressing me out :( 我尝试了很多不同的方法来使它起作用,这确实让我感到压力:(
Have you guyd got any ideas what i'm doing wrong? 您知道我在做什么错吗?
Thanks so much :) 非常感谢 :)
You should look very closely at the way you're using the pointers and its showing in your question... 您应该非常仔细地查看使用指针的方式及其在问题中的显示方式...
void
function.... void
功能...。 See below ... error checking is omitted.... 参见下文...省略了错误检查....
void readfile(FILE* fp,int** storage_array,int lines)
{
int i=0;
for(i=0; i<lines; i++)
{
int readval = 0;
fscanf(fp,"%d",&readval);
*(storage_array[i]) = readval;
}
rewind(fp);
}
In C, a pointer-to-int ( int *
) variable holds the address of an integer, and can also be used for holding the address of the 1st integer in an array of several because you can reach the 2nd and subsequent integers just by adding to the address of the 1st. 在C语言中,指向int(
int *
)的指针变量保存一个整数的地址,并且还可以用于保存多个数组中的第一个整数的地址,因为您可以通过以下方式访问第二个及后续整数添加到第一个的地址。 malloc()
gives you the address of a block of memory which you will use to hold lines
consecutive integers, so you should be storing the address it gives you in a pointer-to-int variable, and the relevant readfile()
parameter should have this type too. malloc()
为您提供一个内存块的地址,该地址将用于存储连续的整数lines
,因此您应将其给您的地址存储在指向int的指针变量中,并且相关的readfile()
参数应具有这种类型也是。
Inside readfile()
, you want to give the fscanf()
call the address of the ith integer. 在
readfile()
内部,您想给fscanf()
调用第i个整数的地址。 You can get this by simply adding i
to the original address, because C takes care of multiplying i
by sizeof (int)
for you: 您可以通过简单地将
i
添加到原始地址中来获得此信息,因为C会为您代以sizeof (int)
来乘以i
:
int *data;
data=malloc(sizeof(int)*lines);
readfile(fp, data, lines);
...
free(data); /* Don't forget to release the memory eventually */
...
int readfile(FILE* fp,int* storage_array,int lines)
{
int i=0;
for(i=0; i<lines; i++)
{
fscanf(fp,"%lf",storage_array+i);
}
rewind(fp);
return 0;
}
The fscanf()
line could be equivalently written fscanf()
行可以等效地编写
fscanf(fp,"%lf",&(*(storage_array+i)));
or even 甚至
fscanf(fp,"%lf",&storage_array[i]);
since in C, the expressions *(a + b)
and a[b]
are equivalent in every way. 因为在C语言中,表达式
*(a + b)
和a[b]
在各个方面都是等效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.