简体   繁体   中英

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.

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'

Kindly advise me, how do I compare two char in different struct, if not using strcmp??

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. 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

struct World{
//variables
}World;

And then struct World would be the same as just saying 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). 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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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