gpt4 book ai didi

比较两个字符 [C 语言]

转载 作者:行者123 更新时间:2023-11-30 16:31:21 27 4
gpt4 key购买 nike

我有一个结构

struct Human {
char *name;
struct location *location;
int cash;
char *weapon;

};

还有一个:

struct World {
char *name;
char *weapon;
int price;
};

这些位于头文件中,并包含在 .c 程序中。

问题

我想比较两个地点的武器是否相同

我尝试过的

int compareWeapons(struct bot *b,int whatToGet) // function signature
struct location *l = b->location;
if ((strcmp(l->weapon,b->weapon) == 0)) { // do stuff }

** 我收到错误消息 **

runtime error: load of null pointer of type 'char'

请告诉我,如果不使用 strcmp,如何比较不同结构中的两个字符?

最佳答案

代码中的问题不是 strcmp 而是空指针,这意味着变量“b”==NULL,因此“b”没有“< strong>location”属性,这就是 NullPointerException 生成的地方。我可能建议检查一下如何将参数传递给函数使用 & 传递变量的地址(指针),或者仅传递变量的名称(如果它是指针)我也不明白类型“机器人”和“位置”我认为你的意思是“struct Human”而不是“struct bot”和“struct World”而不是“struct location” ”您可以命名您的结构,这样您就不必在每个声明处编写结构

struct World{
//variables
}World;

然后struct World将与直接说World相同

关于比较两个字符 [C 语言],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50662586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com