-3

I dunno why this doesn't work. the code has a problem with the *c in charToInt function but should be a legal statement in c. at least so I thought. I am excited to learn something new here.

int charToint(char *c) {
    return *c - '0';  
}

int main(void) {
    char c = '3';
    printf("%d\n", charToint(c));
{
teaNcode
  • 19
  • 1
  • 7

1 Answers1

1

You're passing a char to a function that expects a char *. Your compiler should have warned you about this. The value of that char is then interpreted as a pointer value and dereferenced. Dereferencing an invalid pointer invokes undefined behavior, which in this case results in the program crashing.

The function is ultimately trying to work with a char, so change it to accept a char:

int charToint(char c) {
    return c - '0';  
}

Alternately, you can leave the function as it and pass it a pointer:

printf("%d\n", charToint(&c));
dbush
  • 205,898
  • 23
  • 218
  • 273
  • I'm guessing this wouldn't handle multi-character constants to well (eg. `return *c - '22';`)? – l'L'l Oct 23 '18 at 03:04
  • 1
    How many characters do you think you are allowed to put between single quotes and still have it be a character-constant? (hint: one). If you want an *string-literal* (that can contain more than one char), the wrap it in *double-quotes*. (and note, a string literal should not be modified on the vast majority of systems) – David C. Rankin Oct 23 '18 at 03:22
  • Thank you for the time spent on this. I realize what I did. past by value not by reverence. therefore the function is not seeing the char and is then attempting to access memory it doesnt have. – teaNcode Oct 23 '18 at 03:22
  • @teaNcode Glad I could help. Feel free to [accept this answer](https://stackoverflow.com/help/accepted-answer) if you found it useful. – dbush Oct 23 '18 at 03:24
  • I clicked on the link you gave me, is that all I have to do to accept an answer?? – teaNcode Oct 23 '18 at 03:31
  • @teaNcode The link tells you *how* to accept an answer. Click the green check next to the answer you want to mark. – dbush Oct 23 '18 at 03:32