关于Null vs zero的问题

时间:2010-03-27 17:19:03

标签: c++ string case

我有这个功能:

void ToUpper(char * S)
{
    while (*S!=0)
    {
       *S=(*S >= 'a' && *S <= 'z')?(*S-'a'+'A'):*S;
       S++;
    }
} 

对于* S!= 0是什么意思,如果它是null呢?

5 个答案:

答案 0 :(得分:9)

即检查字符串的结尾,该字符串是值为零的字符。它没有以任何方式连接到NULL指针。

答案 1 :(得分:4)

我会写它*S != '\0'因为我觉得这更加惯用,但这只是个人风格偏好。您正在检查空字符(ASCII NUL)。

您可能还会考虑在任何代码之前检查S != 0,因为指针本身可能为null,并且您不想取消引用空指针。

答案 2 :(得分:0)

NULLCC++

中的定义不同 C

中的

#define NULL 0
C++

中的

#define NULL (void*) 0

答案 3 :(得分:-1)

我比循环更喜欢算法:

#include <algorithm>
#include <cstring>
#include <cctype>

void ToUpper(char* p)
{
    std::transform(p, p + strlen(p), p, toupper);
}

此解决方案也适用于字符编码,其中a到z不是连续的。

只是为了好玩,这是一个只用算法进行一次迭代的实验:

#include <algorithm>
#include <cassert>
#include <cstring>
#include <cctype>
#include <iostream>
#include <iterator>

struct cstring_iterator : std::iterator<std::random_access_iterator_tag, char>
{
    char* p;

    cstring_iterator(char* p = 0) : p(p) {}

    char& operator*()
    {
        return *p;
    }

    cstring_iterator& operator++()
    {
        ++p;
        return *this;
    }

    bool operator!=(cstring_iterator that) const
    {
        assert(p);
        assert(!that.p);
        return *p != '\0';
    }
};

void ToUpper(char* p)
{
    std::transform(cstring_iterator(p), cstring_iterator(),
                   cstring_iterator(p), toupper);
}

int main()
{
    char test[] = "aloha";
    ToUpper(test);
    std::cout << test << std::endl;
}

答案 4 :(得分:-1)

NULL是指针,而* S是存储在指针处的值。感谢Dennis Ritchie,数字0可以作为两者加入。

相关问题