指针诺塔顿有什么问题

what is wrong with pointer notaton

本文关键字:什么 问题 诺塔 指针      更新时间:2023-10-16

我面临的问题是,当我使用指针表示法并运行代码时,它不显示任何内容,当我使用数组表示法时,它会显示期望的结果。我不知道指针符号有什么问题。

#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] != '')
    {
        ptr[count] = tolower(ptr[count]); 
        count++;
    }
    cout<<ptr<<endl; // result is displaying
*/
    while(*ptr != '')
    {
        *ptr = tolower(*ptr); 
         ptr++;
    }   
    cout<<ptr<<endl; // nothing is displaying also no compiler error
    // ptr[0] and ptr[1] als0 displays nothing.
}

while循环中断时,ptr指向字符串末尾的零字节。这就是while (*ptr != '')所做的。所以当你尝试输出ptr时,你正在输出一个空字符串。改为输出str

你必须打印"str"而不是"ptr",因为ptr指向str的末尾。

cout<<str<<endl;

但是,最好执行以下操作:

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