3

I used the function isspace to search through a word for white spaces. The problem is that I get an error message when the program builds: "argument of type char* is incompatible with parameter of type int"

    int const bufferSize = 256;

    newItemIDPointer = (char*)malloc(bufferSize * sizeof(char));
    if (newItemIDPointer == NULL)
    {
        printf("Didnt allocate memory!");
        exit(EXIT_SUCCESS);
    }

    printf("Enter new Item ID: ");
    scanf_s(" %[^'\n']s", newItemIDPointer, bufferSize);

    stringLength = strlen(newItemIDPointer);
    newItemIDPointer = (char*)realloc(newItemIDPointer, size_t(stringLength + 1));

    int i = 0;
    int count = 0;
    while ((newItemIDPointer + i) != '\0')
    {
        if (isspace(newItemIDPointer + i))
        {
            count++;
        }
        i++;
    }

What is wrong with the implementation of isspace in my code and How can I fix this error message?

Breaks Coder
  • 53
  • 3
  • 7

2 Answers2

1

This is because your expression newItemIDPointer + i is a pointer to the character at offset i in the string, not the value (character) at that location. You need to dereference the pointer to get the value, eg:

*(newItemIDPointer + i)

Or a more obvious way to do it is:

newItemIDPointer[i]

To explain: Let's say you have a pointer to a string, called p:

char *p = "ABCDE";

Let's say that the pointer p happens to have a value 0x4001. That would be the address of the first character in your string, which happens to be the letter ASCII value of A (I just totally made that number up, in practice the operating system and/or compiler determine the actual memory location)...

So then, p + 1 will give us 0x4002.. the location of the letter B. It is NOT the ASCII value of B, which happens to be 66 in decimal... That is what you want to be passed to isspace.. the value stored in that memory location, not the address of the memory location.

This is one of the toughest things for beginners to C, once you get a good visual in your head of when you are manipulating the address of a location in memory and when you are manipulating the data stored at that location, the rest of C is pretty easy...

little_birdie
  • 5,600
  • 3
  • 23
  • 28
0

newItemIDPointer + i is a pointer to the i'th character in the string. You don't want the pointer but the character it points to. You need to dereference the pointer.

So replace this:

while ((newItemIDPointer + i) != '\0')
{
    if (isspace(newItemIDPointer + i))

With:

while (*(newItemIDPointer + i) != '\0')
{
    if (isspace(*(newItemIDPointer + i)))

Or equivalently:

while (newItemIDPointer[i] != '\0')
{
    if (isspace(newItemIDPointer[i]))
dbush
  • 205,898
  • 23
  • 218
  • 273