4

I've a function which returns a struct type pointer. What I want is pFacialFeatures to point to the same address as returned pointer.

struct Features
{
    CvRect* face_;
    CvRect* nose_;
    CvRect* eyesPair_;
    CvRect* rightEye_;
    CvRect* leftEye_;
    CvRect* mouth_;
};

Features* Detect()
{
    Features* facialFeatures = (Features*) malloc(sizeof(Features));
    return facialFeatures;
}

int main(int argc, char* argv[])
{
    Features* pFacialFeatures;
    pFacialFeatures = Detect();
}

It gives me the error:

IntelliSense: a value of type "Features *" cannot be assigned to an entity of type "Features *"

Note: Maybe you may think this question is same with this one. In that question there's a problem with declaring struct. I declared struct truely.

Community
  • 1
  • 1
KMetin
  • 133
  • 1
  • 1
  • 11

2 Answers2

2

You have somehow informed Visual Studio that this is a C source file instead of a C++ source file - perhaps by naming the file "something.c" or by placing it in a header file and then including it from a ".h" file or by having a dangling "extern C" or by having somehow set the properties for the file or project to "Compile as C". If you're using Linux/MacOS, you've probably done it by using the C compiler instead of the C++ compiler, e.g. by typing "gcc foo.cpp" instead of "g++ foo.cpp"

The C language syntax for a struct declaration is different than that in C++.

The C++ statement

struct Foo {}; // C++

is equivalent to this in C:

typename struct tagFoo {} Foo; // C

So the following code would work in C++ but fail in C:

struct Foo {};
Foo* f = (Foo*)malloc(sizeof(Foo));

A quick way to change this to check for C++ is to replace:

Features* facialFeatures = (Features*) malloc(sizeof(Features));

with

Features* facialFeatures = new Features;

If you're compiling in C mode, you'll get a compiler error about new. It's a keyword in C++ but not in C.

The way to write your line in C is

struct Features* facialFeatures = malloc(sizeof* facialFeatures);
kfsone
  • 23,617
  • 2
  • 42
  • 74
  • The way to write it in C is `struct Features *facialFeatures = malloc(sizeof *facialFeatures);`. [Don't cast malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – M.M Apr 25 '14 at 04:45
-1

I belive you need to put struct before the declaration of the type:

struct Features* facialFeatures = (struct Features *)malloc(sizeof(struct Features));
bossbarber
  • 870
  • 6
  • 10