简体   繁体   English

如何正确遍历 char 指针?

[英]How to properly iterate through a char pointer?

I am in the process of learning C and I have this issue:我正在学习 C 并且我有这个问题:

main:主要的:

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

}

function: 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.在这种情况下,目标是让 function 只打印“efg”,因为这些值大于或等于字符 e,但最终什么都不会打印,并且 function 退出。 Can someone help me out?有人可以帮我吗? Thanks谢谢

To summarize.总结一下。 There are three things you should keep in mind.您应该记住三件事。

  1. Warnings in C are very important treat them like errors. C 中的警告非常重要,将它们视为错误。
  2. When dealing with pointers, derefrence to compare elements.处理指针时,取消引用以比较元素。
  3. printf family of functions are a little different than other languages, see below. printf 系列函数与其他语言略有不同,见下文。
#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.扩展 function 签名,main 是唯一的例外。 That is the return statement is more or less optional.也就是说,return 语句或多或少是可选的。

The %c on the other hand simply tells the printf function that you are subbing in a character into that string, namely *t .另一方面, %c 只是告诉 printf function 您正在将一个字符插入该字符串,即*t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM