Character pointer to string literal declaration – CSKC
Sign In

Search

Code Learning #CPP#7506    siteicon   siteicon  

Character pointer to string literal declaration

Understanding how character pointer variable is initialised with a string litereal.

Learning Objectives

  • Understanding declaration of a character pointer type variable along with string literal initialisation.
  • Understanding manipulation of character pointers with string functions.
  • Reading character pointers like arrays.

Source Code

TC++ #7506

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Code Understanding

const char *c=”Magic”;
Here c is a pointer type variable that has been initialised with a string literal. The const specifier is needed because from c++ 2003 version on wards string literals are immutable (constant values)

cout<<c[0]<<endl;
This will print M as value at 0th address is M treating as if string literal is a read only array.

int len=strlen(c);
Pointer variables allow string functions.

cout<<len<<endl;
This will print length as 5.

cout<<c[len-1]<<endl;
This will print the last character as last character is denoted by len-1.

//c[4]=’x’;
This has been commented as this can create problems in c++ 2003 version on wards. In previous version this can be done.

cout<<c<<endl;
Pointer variable can be used directly to print whole string, treating them as null terminated string.

Notes

  • Documentation of most string functions will depict parameter to be passed as pointer variable only.


Suggested Filename(s): charptr.cpp, ptr2slit.cpp



Share

Created: 20-Sep-2019 01:06 | Updated: 20-Sep-2019 01:08|