简体   繁体   中英

How can i dereference a pointer to struct in C?

I get an error in the last printf statement: invalid type argument of unary '*'(have'int'). I suppose that * does not dereference the variable "res" because it isn't a pointer to integer. I don't have any idea how to solve the problem. I would really appreciate yor help. Thanks in advance.

//program to find the pair of numbers that summed have has a result a given 
//number n
//ex. input: 8; output: (1,7) (2,6) (3,5) (4,4)
//input: 11; output: (1,10) (2,9) (3,8) (4,7) (5,6)
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int x;
int y;
} couple;
couple* sums(int n)
{
int i;
couple *c = (couple*) malloc(sizeof(couple)*n/2);
for ( i=0; i<n/2; i++)
{
c[i].x = i+1;
c[i].y = n-i-1;
}
return c;
}

int main()
{
    int n,i;
    couple *res;
    scanf("%d",&n);
    res=sums(n);
    for(i=0;i=n/2;i++)
    {
        printf("(%d,%d)",*(res[i].x),*(res[i].y));
    }
    return 0;
}

`

What you have are int s, so no need to use * to dereference.

Also, your loop condition is incorrect. You're doing an assignment where you want a comparison:

for(i=0;i<n/2;i++)
{
    printf("(%d,%d)", res[i].x, res[i].y);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM