#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");
}
In the above code, whenever I replace
(var+count)->
... with var[count]->
it shows the error :" invalid type argument of '->' (have 'struct arr') "
but there is no problem when I use either temp[i]
or temp+i
.
Both var
and temp
are pointers. So why do I get this error ?
Another unrelated question, where or when do I have to free the dynamically allocated pointer temp
. temp
was dynamically allocated inside the function void inputArray(int);
which is called in a loop in main.
(var+count)
!= var[count]
but
*(var+count)
== var[count]
and because
(*(var+count)).temp
or (var+count)-> temp
then
var[count].temp
or (&var[count]) -> temp
MAKE SURE var
is properly initialized and is referencing a valid object before using it!!