首页 > 解决方案 > '->' 的无效类型参数(有 '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+ivar和都是temp指针。那么为什么我会收到这个错误呢?

另一个不相关的问题,我必须在何处或何时释放动态分配的指针temp。在 main 循环中调用temp的函数内部动态分配。void inputArray(int);

标签: carrayspointersmemory-managementstructure

解决方案


(var+count) != var[count]但是

*(var+count) == var[count]

因为

(*(var+count)).temp或者(var+count)-> temp然后

var[count].temp或者(&var[count]) -> temp

确保 var已正确初始化并在使用之前引用有效对象!!


推荐阅读