c - '->' 的无效类型参数(有 'struct arr')
问题描述
#include<stdio.h>
#include<stdlib.h>
struct arr{
int *temp;
int size;
}*var;
void inputArray(int);
void displayArray(int);
int main()
{
int cases,i;
printf("Enter the no of test cases\n");
scanf("%d",&cases);
for(i=0;i<cases;++i)
{
printf("Entering test case %d:\n\n",i+1);
inputArray(i);
}
printf("You have entered the following\n");
for(i=0;i<cases;++i)
{
printf("Test case %d\n\n",i+1);
displayArray(i);
}
return 0;
}
void inputArray(int count)
{
int i;
printf("Enter the size of the array\n");
scanf("%d",&(var+count)->size);
(var+count)->temp=(int*)malloc(sizeof(int)*(var+count)->size);
if((var+count)->temp==NULL)
{
printf("NOT ENOUGH MEMORY IN HEAP");
exit(1);
}
printf("Enter the array\n");
for(i=0;i<(var+count)->size;++i)
{
scanf("%d", &(var+count)->temp[i] );
}
}
void displayArray(int count)
{
int i;
printf("\n");
for(i=0;i<(var+count)->size;++i)
{
printf(" %d ",(var+count)->temp[i]);
}
printf("\n");
}
在上面的代码中,每当我
(var+count)->
用它替换 ... 时var[count]->
都会显示错误:“invalid type argument of '->' (have 'struct arr')” 但是当我使用temp[i]
or时没有问题temp+i
。var
和都是temp
指针。那么为什么我会收到这个错误呢?
另一个不相关的问题,我必须在何处或何时释放动态分配的指针temp
。在 main 循环中调用temp
的函数内部动态分配。void inputArray(int);
解决方案
(var+count)
!= var[count]
但是
*(var+count)
== var[count]
因为
(*(var+count)).temp
或者(var+count)-> temp
然后
var[count].temp
或者(&var[count]) -> temp
确保 var
已正确初始化并在使用之前引用有效对象!!
推荐阅读
- python - Flask-User / Flask-WTForms 中的 reCAPTCHA:“网站验证 reCAPTCHA 通过解决方案的时间少于 50%”?
- ios - 尝试下载文件时出现 Swift Alamofire 错误
- c# - 在 LINQ 选择中使用公式
- javascript - 本机 JS Ajax 向 ASP.Net 发布的对象为空
- c# - C#打印机本地打印机安装处理
- vhdl - VHDL用类型的最大值初始化信号
- firebase - Google AutoML Vision - 如何调用多个预测
- python - Selenium 稍后不会加载元素
- spring - Spring Integration 在聚合后调用另一个处理程序方法
- wxpython - 是否可以在 wxPython 中更改滑块的粗细?