【发布时间】:2020-06-30 13:44:14
【问题描述】:
#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] 或temp+i 时都没有问题。
var 和 temp 都是指针。那么为什么会出现这个错误呢?
另一个不相关的问题,我必须在何处或何时释放动态分配的指针temp。 temp 是在函数 void inputArray(int); 内动态分配的,该函数在 main 的循环中调用。
【问题讨论】:
-
除了编译错误之外,在任何一种情况下,您都不会为
var分配任何值,因此您不能像这样做那样取消引用它。您的程序有未定义的行为。 -
首先,全局指针变量
var是NULL,因为它没有被显式初始化,所以已经“暂时定义”了一个默认初始值NULL。跨度> -
抱歉我忘了加
var=(struct arr*)malloc(sizeof(struct arr)*cases); -
在实际分配内存之前,您不能将数据存储在分配的内存中...
标签: c arrays pointers memory-management structure