asa
asa

Reputation: 57

How can i compare an int pointer with a char pointer?

In my code i'm trying to do a comparison between an int pointer and a char pointer. The char pointer is supposed to hold an integer after i strrchr the full string. I then want to see if the integer is larger than another integer that is stored in an int pointer. Using strcmp, or just doing >= will give me a warning. Assume that an int will always be present after the semicolon.

typedef struct songInfo
{
 int* ratingScore;
 char songName[80];
 struct songInfo *prev;
 struct songInfo *next;
 }songInfo;

int main()
{
 songInfo *head = NULL, *tail = NULL;
 ...
}


int insert(char *buffer, songInfo **head, songInfo **tail)
{
 ...
 char* rating = strrchr(song, ';');
 rating++;
 if ((*head)->ratingScore >= rating)
 ...
}

Upvotes: 0

Views: 806

Answers (3)

egabs
egabs

Reputation: 21

rating points to ';' rating+1 points to your integer let's say A A = atoi(rating+1) So here it goes:

char* rating = strrchr(song, ';');
if ((*head)->ratingScore >= atoi(rating+1))

Now that you showed that ratingScore is not an integer but a pointer to an integer you just need to dereference that pointer. So here it goes:

char* rating = strrchr(song, ';');
if (*((*head)->ratingScore) >= atoi(rating+1))

Upvotes: 0

ilim
ilim

Reputation: 4547

You first need to convert the string representation of the integer(the one pointed to by rating) that was typed into the string to a second integer to compare its value to the integer pointed to by int pointer you mention.

You may use a function such as sscanf to read the string representation into an integer and you can compare the value read with the one pointed to by the integer pointer. Below is a sample code that may more or less achieve what you are attempting to do.

int tmp;
sscanf(rating+1, "%d", &tmp); // +1 is to skip the ';' character
if( *(*head)->ratingScore >= tmp)
{
    ...
}

Notice that the dereferencing operator for ratingScore was added due to your mention of the type of ratingScore being an int* in the comments to my answer. (Also note that I do not understand why you would keep it as an int*, but the code above should satisfy your constraints nonetheless)

Here's a sample usage of this idea at work.

Upvotes: 2

Romain Artru
Romain Artru

Reputation: 65

Well, of of course you cannot compare 2 pointers of different types, but anyway it seems to me that you are more trying to compare the values pointed than the pointers. As @ilim said, you want to use strtol(*rating, NULL, 0) or something similar.

Upvotes: 0

Related Questions