C++如何创建和使用指针来查找字符数组的长度
C++ How to create and use a pointer to find length of a character array?
我想找到字符数组的长度。我试图创建一个指针,但它没有任何意义。程序的另一部分,我需要将我已经做过的名字大写。我知道有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;
}
希望它能有所帮助
非常感谢。
相关文章:
- 重载解析、名称查找和函数指针
- 有没有办法在递归中使用指针来查找数组的最小值?
- 查找排序的容器,其中指向元素的指针在添加/删除时不会更改
- 如何查找指向数组中元素的指针的索引
- 查找并将指针返回向量中的对象
- 如何从链表指针字符中查找字符
- 指向符号的指针与常规符号查找的 ABI 稳定性
- 如何通过也在向量中的指针查找作为类成员的向量的大小
- 使用C RTTI(内置)通过字符串查找功能指针
- 如何通过将数组的指针传递给函数来查找数组的模式?C++
- 如何在具有非常量指针键的地图中通过常量指针键查找
- 无法使用指针查找正确的元素 - 从函数返回时,对象上的 poiting 为 null
- 如何在 c++ 中查找文件指针位置
- 从堆栈指针中查找函数参数值
- 使用动态内存分配和指针查找最大值、最小值和平均值
- std::在对象指针的向量上查找
- 反向查找指针,以n在CSTRING中出现一个字符
- 使用原始内存地址查找指针/类
- 正在查找指针的类型
- 查找指针指向的数组的大小