CD S
CD S

Reputation: 53

counting characters to reach null character

#include<iostream>

using namespace std;

char extract(char* ch);

int main()
{
    char* p_char = new char;
    *p_char = 'p';
    cout << "the address of p_char  " << &p_char << endl;
    cout << "the value of p_char  " << (void*)p_char << endl; // To show the value of pointer that appointing char type, use typecast(void*).
    cout << "the value of p_char  " << p_char << endl;  //this cout prints the value which is in p_char from the first character,which is p, to null character.
    cout << extract(p_char);
    cout << "the value of the address that is the value of  p_char  " << *p_char << endl;

    delete p_char;
    return 0;
}

char extract(char* ch)
{
    int n = 0;
    char k;
    while (*ch != '\0')
    {
        n++;
        ch++;
    }
    cout << "n = " << n;
    k = '\n';
    return k;
}

What I intended to make is that from cout << "the value of p_char " << p_char << endl; strange sentence, starting with p, is printed out.

And the strange sentence ends because of null character which is randomly placed.

So, the user defined function extract() count how many characters exist from starting p to ending null character.

function parameter (argument) ch is a pointer which directs char type.

So, ch++ adds 1 byte to ch.

When I press compile button, the outcome is like below.

the address of p_char  00FAFBE4

the value of p_char  01509C78

the value of p_char  p羲羲硼?뺯퍈

n = 14

the value of the address that is the value of  p_char  p

As I understand, the character p is stored in address 01509C78 and "羲羲硼?뺯퍈" these are stored continuous location from 01509C78.

So, p羲羲硼?뺯퍈'\0' is completed.

But, when I use cout << sizeof("p羲羲硼?뺯퍈")<<" bytes"; The consequence is 14 bytes. This 14 bytes is including the null character which is automatically added in string constant.

So pure bytes of p羲羲硼?뺯퍈 are 13 bytes.

My question is, why n is 14 and not 13?

The initial value of n is 0, ch++ adds 1 byte every term of while, and the size of p羲羲硼?뺯퍈 is 13 bytes.

Upvotes: 1

Views: 90

Answers (1)

eerorika
eerorika

Reputation: 238391

The behaviour that you observe is because the behaviour of the program is undefined. You access memory outside the bounds of the object.

Upvotes: 2

Related Questions