apkim221
apkim221

Reputation: 121

Why am I getting an "assignment from incompatible pointer type" error?

I keep getting this error, but cannot figure out why. Any help would be greatly appreciated.

This is my stock.h file.

typedef struct stock {

char *stockSymbol;
float closingSharePrice;
float openingSharePrice;
int numberOfShares;
float (* getPrice) (void * S);
float (* getTotalDollarAmount) (void * S);
float (* getPercentChange) (void * S);
char * (* toString)(void * S);

 } stock_t; 

float returnPrice (stock_t *S);
float returnTotal (stock_t *S);
float returnPercentChange (stock_t *S);
char * returnString (stock_t *S);

And this is my stocks.c file.

#include <stdio.h>
#include <stdlib.h>
#include "stocks.h"

float returnPrice (stock_t *S) {

S->getPrice = returnPrice;

    }

It is in the .c file in the line where I set the getPrice pointer equal to the returnPrice function and I get the error. How should I define assign getPrice so that it points to the returnPrice function? Thanks in advance.

Upvotes: 1

Views: 8996

Answers (3)

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

float (*) (void*) and float (*) (stock_t*) are different types, hence the complaint.

To define your function you can use e.g. this syntax:

typedef struct stock stock_t;
struct stock {
   ...
   float (* getPrice) (stock_t * S);
   ...
};

Do not use void* and casts unless you absolutely have to. In this case you don't have to. Other answers tell you to go ahead and use void*. I respectfully submit that this is ill-advised.

I'm not sure why you would do the function pointer assignment at the place you do. This is probably wrong, though has nothing to do with the compiler message.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477030

It's because S->getPrice is a pointer to a float(void *), but returnPrice is a float(stock_t *). Those are not the same, nor are they compatible.

You could fix it by changing the function signature:

float returnPrice(void * p)
{ 
    stock_t * S = p;
    S->getPrice = &returnPrice;
}

Upvotes: 0

K Scott Piel
K Scott Piel

Reputation: 4380

The prototype that setPrice expects is float (* getPrice) (void * S); which means that setPrice expects the argument to the function to accept a pointer to any data type. However, your returnPrice method is more restrictive as float returnPrice (stock_t *S) so it only works with/expects a stock_t* as an argument and therefore does not meet the criteria for a setPrice pointer.

You would need to declare float returnPrice (void *S) and then cast S inside the function for it to work correctly. Or cast the function pointer itself.

typedef float (*GetPriceFunction) (void * S);

typedef struct stock 
{
    GetPriceFunction getPrice;
}

S->getPrice = (GetPriceFunction)returnPrice;

Upvotes: 3

Related Questions