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

为何char*数组下标访问结果为char*?传参类型不匹配报错求助

指针数组传参类型不匹配问题解决

问题概况

  • 代码定义:char* chunktl[140];(原本误以为是char数组,实际是char指针数组,每个元素都是指向char的指针)
  • 索引计算:int arrayloc = relx + 7 +(8-rely)*16;
  • 调用函数:pixrender(chunktl[arrayloc]);触发编译错误

报错信息

error: passing argument 1 of ‘pixrender’ makes integer from pointer without a cast [-Wint-conversion]
  206 |                                                 pixrender(chunktl[arrayloc]);
      |                                                           ~~~~~~~^~~~~~~~~~
      |                                                                  |
      |                                                                  char *
terraria.c:81:22: note: expected ‘char’ but argument is of type ‘char *’
   81 | char* pixrender(char a)
      |                 ~~~~~^

核心疑问与解答

1. 为什么修改arrayloc的类型(unsigned int、long等)没用?

错误根源和索引类型无关,是数组元素的类型与函数参数类型不匹配。不管arrayloc是int还是long,chunktl[arrayloc]取到的都是数组里的char*指针,而pixrender需要的是char类型的单个字符,类型不兼容的问题不会因为索引类型改变而消失。

2. 为什么char* 数组[整数索引]的结果是char*类型?

char* chunktl[140]的定义是:创建一个包含140个元素的数组,每个元素的类型都是char*(指向char的指针)。用索引访问数组时,得到的就是对应位置的char*元素。比如如果chunktl[0] = "test",那么chunktl[0]是指向字符串"test"首地址的指针,而*chunktl[0]才是字符串的第一个字符't'。

解决方案

根据实际需求二选一:

  • 如果chunktl[arrayloc]指向的是一个字符串,需要传递这个字符串里的某个字符(比如第一个字符),修改调用语句为:
    pixrender(*chunktl[arrayloc]);
    
    这里的*是解引用操作,把char*指针转换成它指向的char值。
  • 如果本意是让chunktl存储char类型数据,直接修改数组定义为普通char数组:
    char chunktl[140];
    
    这样chunktl[arrayloc]就是char类型,符合pixrender的参数要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:22:33