1

I am trying to achieve some thing similar to this question: link

I have this in code:

#include <stdio.h>
#include <stdlib.h>
struct a *prepareStructA(void);

struct abstract
{
  int x;
  int y;
  int radius;
};

struct a
{
  struct abstract abs;
  //... other data ...
};

//OR Smarter way:
void foo2(struct abstract *data)
{
  int x,y,r;
  x = data->x;
  y = data->y;
  r = data->radius;
}
//Calling foo2 with:
main(){
struct a *sa = prepareStructA();
foo2(sa->abs);
}

but I get this error:

incompatible type for argument 1 of ‘foo2’

expected ‘struct abstract *’ but argument is of type ‘struct abstract’
void foo2(struct abstract *data)

if I change "*data" to "data" i get segmentation error. Can someone please help me out. What I am actually trying to achieve is to pass different structures to same function and perform same operations on them. So any insight on that would be helpful too. Thanks in advance!

Community
  • 1
  • 1
sonalkr132
  • 967
  • 1
  • 9
  • 25
  • Besides you probably don't want to pass the structure by-value anyway and you have your answer, I'm a little surprised about the segfault… – mafso Aug 21 '14 at 17:52

1 Answers1

4

You need to pass in the address of the struct:

foo2(&(sa->abs));
jh314
  • 27,144
  • 16
  • 62
  • 82
  • 1
    yay! it works. Thanks you so much. btw.. I had to change struct a *sa = prepareStructA(); to struct a *sa = (struct a *) malloc(sizeof(struct a)); too. no idea what was prepareStructA() for. – sonalkr132 Aug 21 '14 at 18:04