c - "cannot convert to a pointer type"C

标签 c pointers

<分区>

我正在使用我编写的通用堆栈库编写一个后缀计算器。首先我要说这是一项家庭作业,我通常不会在线寻求帮助,但辅导中心/帮助室今天关闭。

我有一个函数“calc”,它从 stdin 获取字符输入,对其进行标记化,并确定它是否为数字、+-*^。分词器可以正常工作,因为我之前已经在所有情况下对其进行了测试。

我实现堆栈库时似乎有问题。

这是有问题的代码:

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;

还有其他 switch 语句可以处理其他字符(+、-、* 和 ^),但我还没有继续讨论它们。

思路是将字符数组num转为 float 。

push 函数是我的堆栈库的一部分。这是相关代码:

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)++;
}

堆栈库按照我的预期工作,因为我以前在其他程序中使用过它,所以我并不担心。

我的问题是,当我编译后缀计算器时,出现错误“无法转换为指针类型”,它引用了这一行:

push(stk, (void *)n); 

我现在要做的就是从 stdin 获取用户输入,将其压入堆栈,从堆栈中读取,然后将其从堆栈中弹出。我不确定为什么我现在会收到此错误,而且我不确定如何修复它。非常感谢任何帮助或提示让我朝着正确的方向前进。

最佳答案

floatdouble 与整数类型不兼容,你不能将它们转换为指针,你想要的是在堆栈上使用 float,或者指向花车:

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

要使用栈中的元素,将其转换回来:

float *f = pop(stk);  // I assume your pop function returns a void *
float n = *f;  // n is the number your pushed

关于c - "cannot convert to a pointer type"C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36973650/

相关文章:

c - 在C中获取指针数组的第一个元素?

c - 返回函数时出现段错误错误

c - 如何在宏中使用 __func__

java - 用Java模拟一个指针?在 Kotlin ?

c++ - 无法通过函数指针c++执行类函数

c - C 中的动态结构

c - 如何在 gtk 中刷新图像?

c++ - 错误 C2679 : binary '=' : no operator found which takes a right-hand operand of type 'School *' (or there is no acceptable conversion)

c# - 在 C# 中用另一个对象实例替换对象实例

c++ - 结构原型(prototype)问题(未定义类型的无效使用)c++