*Beginner* C: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'

StackOverflow https://stackoverflow.com/questions/19873562

  •  29-07-2022
  •  | 
  •  

Question

I'm trying to convert each letter in a string to it's ASCII number. Using

 int letter = (atoi(ptext[i]));

gives me this error:

error: incompatible integer to pointer conversion
  passing 'char' to parameter of type 'const char *'; take the
  address with & [-Werror]
    int letter = (atoi(ptext[i]));
                       ^~~~~~~~
                       &
/usr/include/stdlib.h:148:32: note: passing argument to parameter
      '__nptr' here
extern int atoi (__const char *__nptr)

Here is some of the rest of my code that may be relevant:

    #include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, string argv[])
{

    printf("Give a string to cipher:\n");
    string ptext = GetString();

    int i = 0;

    if (isupper(ptext[i]))
    {
        int letter = (atoi(ptext[i]));
    }
}

What am I doing wrong, and how do I fix this so I can convert a string into ASCII values?

Note: cs50.h lets me use "string" instead of "char*" in main.

Was it helpful?

Solution 2

You do not need to convert characters to a number. It is a matter of interpretation of your data.

Charater 'A' can be thought of 0x41 or 65 so this is perfectly fine:

int number = 'A';

and value on variable number is 0x41/65 or 1000001b depending how you want to present it/treat it.

As for interpretation : 0xFF may be treated as 255 if you present it as unsigned value or even as -1 when treated as signed and kept in 8 bits.

So your question:

can convert a string into ASCII values?

is kind of wrong - all characters of the string are already ascii values - it is just a matter of how you treat/print/interpret/present them.

OTHER TIPS

atoi() expects a string. You only want the char code of the character... which is the character itself, since in C, the char is a normal integer type just like every other integer, and a string is an array of chars which hold the character codes themselves.

Consequently,

int letter = ptext[i];

would do the job.

int letter = (atoi(ptext[i]));

atoi() convert string to integer not character.

To store ascii value of character into integer variable Do direct assignment of character to integer variable.

int letter = ptext[i];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top