简体   繁体   English

指针notaton有什么问题

[英]what is wrong with pointer notaton

The problem I am facing is that when I use pointer notation and run the code it displays nothing and when I use array notation it displays the desire result. 我面临的问题是,当我使用指针表示法并运行代码时,它什么都不显示,而当我使用数组表示法时,它显示期望的结果。 I don't know what is wrong with the pointer notation. 我不知道指针表示法出了什么问题。

#include <iostream>
#include <cctype>
#include <cstring>

using namespace std;

int main()
{
    char str[30] = "PROGRAMMING IS FUN";
    char* ptr = str;
/*
    int count=0;

    while(ptr[count] != '\0')
    {
        ptr[count] = tolower(ptr[count]); 
        count++;
    }

    cout<<ptr<<endl; // result is displaying
*/

    while(*ptr != '\0')
    {
        *ptr = tolower(*ptr); 
         ptr++;
    }   

    cout<<ptr<<endl; // nothing is displaying also no compiler error

    // ptr[0] and ptr[1] als0 displays nothing.
}

When the while loop breaks, ptr is pointing to the zero byte at the end of the string. while循环中断时, ptr指向字符串末尾的零字节。 That's what while (*ptr != '\\0') does. 这就是while (*ptr != '\\0')所做的事情。 So when you try to output ptr , you're outputting an empty string. 因此,当您尝试输出ptr ,您将输出一个空字符串。 Output str instead. 输出str

You have to print "str" instead of "ptr", because ptr is pointing to the end of str. 您必须打印“ str”而不是“ ptr”,因为ptr指向str的结尾。

cout<<str<<endl;

However, it would be beter to do the following: 但是,最好执行以下操作:

int len = strlen(str);
for(int i = 0; i<len; i++){
 str[i] = tolower(str[i]);
}

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

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