【问题标题】:Comparing Two Char [in C]比较两个字符 [在 C 中]
【发布时间】:2018-06-03 01:41:35
【问题描述】:

我有一个结构

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 }

** 我收到错误消息 **

运行时错误:加载“char”类型的空指针

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

【问题讨论】:

  • 你的stuct位置真的有field char*武器?

标签: c char compare


【解决方案1】:

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

struct World{
//variables
}World;

然后 struct World 就等于说 World

【讨论】:

    【解决方案2】:

    问题不在于您的字符串比较,而在于您声明结构的方式。

    您似乎正在使用 (struct bot *) 来引用 (struct Human)。 在这种情况下,它应该看起来:

    int compareWeapons(struct World *b, int whattoget);
    

    此外,您的结构位置必须初始化,否则您引用的结构不包含任何内容 (NULL)。

    struct location
    {
        //your struct variables
    };
    

    下面是一个关于如何初始化结构的基本示例的链接,https://www.cs.usfca.edu/~wolber/SoftwareDev/C/CStructs.htm

    【讨论】:

      猜你喜欢
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多