Mary
Mary

Reputation: 211

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

I want to find the length of the character array. I tried to create a pointer but it did not count anything. There is another part to the program where I need to capitalize the name which I already did. I know there is strlen but my instructions are to not use it.

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 != '\0')
    {
        length++; 
        ptr++;  `enter code here`
    }
    cout << "The length of the character is " << ptr++ << "." << endl; 

    cout << endl;
    system("PAUSE"); 
    return 0;
}
//end main

Upvotes: 1

Views: 79

Answers (3)

songyuanyao
songyuanyao

Reputation: 172864

You have assigned ptr to name, there's no need to new it again. Delete this:

ptr = new char;

and you're not printing out the length of array, you should print out length:

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

Upvotes: 2

Razib
Razib

Reputation: 11153

Your code is almost correct except you don't need to add the following line in your code -

ptr = new char; 

And print the length instead of ptr. If I rewrite the code with these correction then it will be -

#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 != '\0')
    {
        length++;
        ptr++;
    }
    cout << "The length of the character is " << length<< "." << endl;
    cout << endl;
    //system("PAUSE");
    return 0;
}

Hope it will help.
Thanks a lot.

Upvotes: 0

justin.m.chase
justin.m.chase

Reputation: 13655

What you have is almost right. The idea is to scan through the string by incrementing a pointer looking for '\0'. The only major bug you have is that the while condition should be:

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

You should rename SIZE to MAX_LENGTH and drop the +1's. If you don't stop at MAX_LENGTH what you have is known as a buffer overflow bug.

Upvotes: 0

Related Questions