Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

c - Why can't my function take in a char variable type?

Here is the code:

#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>

bool isHex(char * str[20]){
    return isxdigit(str);
}

int main(){
    printf("%d
", isHex("A8"));
    return 0;
}

I get the following message when I try to compile:

ishex.c:6:21: warning: incompatible pointer to integer conversion passing 'char **' to parameter of type 'int' [-Wint-conversion] return isxdigit(str); ^~~ /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/_ctype.h:280:14: note: passing argument to parameter '_c' here isxdigit(int _c) ^ ishex.c:13:26: warning: incompatible pointer types passing 'char [3]' to parameter of type 'char **' [-Wincompatible-pointer-types] printf("%d ", isHex("A8")); ^~~~ ishex.c:5:19: note: passing argument to parameter 'str' here bool isHex(char * str[20]){

What is the issue in my code? I just want it to return true (1) if the string is a valid hex character, and false (0) if the string is not a valid hex character.

question from:https://stackoverflow.com/questions/65947308/why-cant-my-function-take-in-a-char-variable-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You've got two problems. First, your function as defined takes an array of char pointers and yet you're passing in a single const char*. Second, isxdigit takes a single char and not an array of char*. You should change your function to

bool isHex(const char *str)
{
    size_t len;

    if ( str == NULL ) { // In general, you need to protect your functions from bad arguments.
        return false;
    }

    len = strlen(str);
    for (size_t k=0; k<len; k++) {
        if ( !isxdigit(str[k]) ) {
            return false;
        }
    }

    return true;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...