-2

Hi i have the below code and for some reason am getting the error and can't seem to work out why.

warning: return makes integer from pointer without a cast

The code i have is:

long convertToInt(char *convert) {
        char *p = convert;
        while(*p){
            if(isdigit(*p)) {
                long val = strtol(p, &p, 10);
                return val;
            } else {
                p++;
            }
        }
    return NULL;
}
move
  • 57
  • 4

4 Answers4

2

NULL is a pointer, not an integer. It may be implemented as a #define that expands to 0 (the integer constant) or ((void *)0) the null pointer constant. If you want to return a value that means "an error occurred", you'll probably want to return an integer constant. Values 0 and -1 are traditional.

Even better is to returns a boolean status value for success/failure, and return the value via a pointer argument: bool_t convertToInt(const char *s, long *value). See the standard library function strtol for an example.

1

Your funtion returns long. So change the return statement to:

return 0L;

One possible definition of NULL is (void *)0 which is being converted to long when you return.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
1

The proper code would be, assuming convert is a string with the digits:

long convertToLong(char *convert) {
    long val = 0L;
    char *p = convert;
    while (isdigit(*p)){
        val = val * 10 + (*p - '0');
        p++;
    }
    return val;
}
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
0

The problem is here:

return NULL;

where you return NULL, but the return type of the function is long.


Moreover your function is named convertToInt(), but it returns a long, which would imply a convertToLong() function name.

gsamaras
  • 71,951
  • 46
  • 188
  • 305