CeilingSystems
CeilingSystems

Reputation: 187

How to properly iterate through a char pointer?

I am in the process of learning C and I have this issue:

main:

int main()
{
    char str[] = "abcdefg";
    countRange(str, 'e');

}

function:

int countRange(char* str, char c1)
{
    char *t;
    for (t = str; *t != '\0'; t++)
    {
        if ((t >= c1))
        {
            printf(t);
        }
    }
}

In this case, the goal would be for the function to only print "efg", since those values are greater than or equal to the character e, however nothing ends up getting printed and the function exits. Can someone help me out? Thanks

Upvotes: 1

Views: 2997

Answers (1)

ysftaha
ysftaha

Reputation: 21

To summarize. There are three things you should keep in mind.

  1. Warnings in C are very important treat them like errors.
  2. When dealing with pointers, derefrence to compare elements.
  3. printf family of functions are a little different than other languages, see below.
#include <stdio.h>

/**
  * Since the function returns nothing it returns `void`
  */
void countRange(char str[], char c1)
{
    char *t;
    for (t = str; *t != '\0'; t++)
    {
        if ((*t >= c1)) // *t refers to the char. using t would be the whole string
        {
            printf("%c", *t); // printf prints strings only
        }
    }
}

int main()
{
    char str[] = "abcdefg";
    countRange(str, 'e');
}

Expanding on function signature, main is the only exception. That is the return statement is more or less optional.

The %c on the other hand simply tells the printf function that you are subbing in a character into that string, namely *t.

Upvotes: 2

Related Questions