C++如何创建和使用指针来查找字符数组的长度

C++ How to create and use a pointer to find length of a character array?

本文关键字:查找 指针 字符 数组 何创建 创建 C++      更新时间:2023-10-16

我想找到字符数组的长度。我试图创建一个指针,但它没有任何意义。程序的另一部分,我需要将我已经做过的名字大写。我知道有strlen,但我的指示是不要使用它。

const int SIZE = 25;   // Array size
int main()
{
    char name[SIZE+1] = "john smythe";  // To hold a name
    int length = 0; //for length of array
    //To get length of char name
    char *ptr = name; 
    ptr = new char; 
    while (*ptr != '')
    {
        length++; 
        ptr++;  `enter code here`
    }
    cout << "The length of the character is " << ptr++ << "." << endl; 
    cout << endl;
    system("PAUSE"); 
    return 0;
}
//end main

您已将ptr分配给name,无需再次新建。删除此:

ptr = new char;

如果你没有打印出数组的长度,你应该打印出length:

cout << "The length of the character is " << length << "." << endl; 

您所拥有的几乎是正确的。其想法是通过增加寻找"\0"的指针来扫描字符串。你唯一的主要错误是while条件应该是:

while (*ptr != '' && length < MAX_LENGTH) 

您应该将SIZE重命名为MAX_LENGTH并删除+1。如果你不停在MAX_LENGTH,你就会发现一个缓冲区溢出错误。

您的代码几乎是正确的,只是您不需要在代码中添加以下行-

ptr = new char; 

并打印长度而不是ptr。如果我用这些更正重写代码,那么它将是-

#include<iostream>
using namespace std;
const int SIZE = 25;  
int main()
{
    char name[SIZE+1] = "john smythe"; 
    int length = 0; 
    char *ptr = name;
    //ptr = new char;
    while (*ptr != '')
    {
        length++;
        ptr++;
    }
    cout << "The length of the character is " << length<< "." << endl;
    cout << endl;
    //system("PAUSE");
    return 0;
}

希望它能有所帮助
非常感谢。