You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言编译报错:void*无法赋值给char*,求问题原因与解决方法

问题原因

你遇到的错误是因为C++编译器不允许void*类型隐式转换为其他指针类型,而malloc和realloc的返回值是void*。如果你的代码是用C++编译器(比如g++)编译的,就会触发这个错误;但用C编译器(比如gcc)编译的话,C语言本身支持void*到其他指针的隐式转换,不会报错。

解决方案

有两种解决方式:

  • 用C编译器编译代码,比如执行命令:gcc your_file.c -o your_program
  • 给malloc和realloc的返回值添加显式强制类型转换,将void*转为char*
修改后的完整代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *readLine(int size) {
    char *str;
    int ch;
    int len = 0;
    // 添加(char*)强制类型转换
    str = (char*)malloc(size);
    if (str == NULL) {
        fprintf(stderr, "malloc error\n");
        exit(1);
    }
    while ((ch = getchar()) != EOF && (ch != '\n')) {
        str[len++] = ch;
        if (len == size) {
            size = size * 2;
            // 添加(char*)强制类型转换
            str = (char*)realloc(str, size);
            if(str == NULL) {
                fprintf(stderr, "realloc error\n");
                exit(1);
            }
        }
    }
    str[len] = '\0';
    return str;
}

内容的提问来源于stack exchange,提问作者Mitchell Leefers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 16:35:23