Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"cannot convert to a pointer type" C [duplicate]

Tags:

c

pointers

I'm writing a postfix calculator using a generic stack library I wrote. I will preface this by saying that it is a homework assignment, and I normally wouldn't seek help online, but the tutoring center / help room is closed today.

I have a function "calc" that takes character inputs from stdin, tokenizes it, and determines if it is a number, +, -, *, or ^. The tokenizer works, as I have tested it before with all cases.

There seem to be issues when I implement the stack library.

This is the code in question:

char num[MAX_NUM];
float n;
while (1) {
            switch (token = get_tok(num, sizeof(num))) {
            case TOK_NUM:
                    //printf("TOK_NUM: %s (%lf)\n", num, strtod(num, NULL));
                    n = strtod(num, NULL);
                    push(stk, (void *)n);        
                    printf("TOK_NUM_STK: %lf\n", (float)peek(stk));
                    pop(stk);
                    break;

There are other switch statements to deal with the other characters (+, -, *, and ^) but I haven't moved on to them yet.

The idea is to convert the character array num to a floating point.

The push function is a part of my stack library. This is the code for that:

struct stack_t {
    int count;
    struct node_t {
            void *data;
            struct node_t *next;
    } *head;
};

void push(stack stk, void *data) {

    struct node_t *tmp = malloc(sizeof(struct node_t));

    tmp -> data = data;

    tmp -> next = stk -> head;

    stk -> head = tmp;

    (stk -> count)++;
}

The stack library works as I expect it to, as I have used it in other programs before, so I'm not worried about that.

My problem is that when I compile my postfix calculator, I get the error "cannot convert to a pointer type" and it references this line:

push(stk, (void *)n); 

All I'm trying to do right now is take the user's input from stdin, push it onto the stack, read it from the stack, and then pop it off the stack. I'm not sure why I'm getting this error right now, and I'm not sure how to fix it. Any help or tips to move me in the right direction would be greatly appreciated.


1 Answers

float and double are not compatible with integer types, you cannot convert them to pointer, what you want is either use float on the stack, or a pointer to the floats:

float *f = malloc(sizeof *f);
*f = n;
push(stk, f);

To use the elements on the stack, convert it back:

float *f = pop(stk);  // I assume your pop function returns a void *
float n = *f;  // n is the number your pushed
like image 94
fluter Avatar answered May 30 '26 10:05

fluter