简体   繁体   English

比较两个字符[C]

[英]Comparing Two Char [in C]

I have a struct 我有一个结构

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

};

and another one: 还有一个:

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

These are in header files, and included in a .c program. 这些位于头文件中,并包含在.c程序中。

Question

I want to compare if the weapon is the same as in both locations 我想比较一下两个地方的武器是否相同

What I tried 我尝试了什么

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

** Error message I get ** **错误消息我得到**

runtime error: load of null pointer of type 'char' 运行时错误:加载类型为'char'的空指针

Kindly advise me, how do I compare two char in different struct, if not using strcmp?? 请告诉我,如果不使用strcmp,我该如何比较不同结构中的两个char?

The problem in your code is not the strcmp but the null pointer which means that the variable " b "==NULL,so " b " has no " location " attribute and that's where the NullPointerException generates. 您代码中的问题不是strcmp而是空指针,这意味着变量“ b ” == NULL,因此“ b ”没有“ location ”属性,而这正是NullPointerException生成的地方。 I may suggest to check how you pass the arguments to your function Use & to pass the address (pointer) of your variable or just the name of your variable if it's a pointer Also I didn't understand the type " bot " and " location " I think you meant " struct Human " not " struct bot " and " struct World " not " struct location " You can name your struct so you don't have to write struct at each declaration 我可能建议检查如何将参数传递给函数使用传递变量的地址(指针)或变量的名称(如果是指针的话)。我也不理解类型“ bot ”和“ location”。 “我认为您的意思是“ struct Human ”而不是“ struct bot ”,而不是“ struct World ”而不是“ struct location ”。

struct World{
//variables
}World;

And then struct World would be the same as just saying World 然后struct World就跟说World一样

The problem is not your string compare, it's how you are declaring your structs. 问题不是您的字符串比较,而是您声明结构的方式。

It seems you are using (struct bot *) to reference the (struct Human). 似乎您正在使用(struct bot *)引用(struct Human)。 In that case it should look: 在这种情况下,它应该看起来像:

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

Additionally your struct location must be initialized or else you are referencing a struct that contains nothing (NULL). 此外,必须初始化您的结构位置,否则您将引用不包含任何内容的结构(NULL)。

struct location
{
    //your struct variables
};

Below is a link with a basic example on how to initialize a struct, https://www.cs.usfca.edu/~wolber/SoftwareDev/C/CStructs.htm 以下是有关如何初始化结构的基本示例的链接, https://www.cs.usfca.edu/~wolber/SoftwareDev/C/CStructs.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM