Passing null terminated string to function using pointer notation – CSKC
Sign In

Search

Code Learning #CPP#2706    siteicon   siteicon  

Passing null terminated string to function using pointer notation

Program to pass by reference character array as a null terminated string to a function using the pointer notation using *.

Learning Objectives

  • To pass c-style string (null terminated character array) as a function argument using the pointer notation *.

Source Code

TC++ #2706

 

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

Alternate (?) :

Code Understanding

int space_count(char *);
This is function prototype with char array passed using pointer * notation.

char str[80]; int spaces=0; //Initialisations as required.
cout<<“Input a small sentence: ” ; cin.getline(str,80); //Collecting user input sentence.

spaces=space_count(str);
function calling. When  we give the array name, we are actually passing the address of the first member of array.

cout<<“Number of spaces in given input = “<<spaces<<endl;
Final output printing.

int space_count(char *str)
Function definition where the array name with * notation is passed.
{
int sp_count=0; //Initial value 0 needed so that junk value is not stored.
int len=strlen(str); //strlen can be found as the passed array is actually a null terminated string.
for(int i=0;i<len;i++) //Loop till number of characters time.
if(str[i]==’ ‘) sp_count++; //increment count the moment space ‘ ‘ character is found.
return sp_count; //Return the given count to the calling function as an integer value.
}

Notes

  • array notation and pointer notation can be interchangeably used for passing arrays, but professional programmers prefer to use the pointer notation.
  • This program has an assumption that the character array passed is actually a null terminated string. If the null termination is not there, the functions like strlen() etc. will not work. For other types of array say integer array or character array without null, passing the array length as another parameter will be required.

Common Errors

  • sometime student give pointer notation as char str* which is incorrect. It can be –
    char* str or char *str


Suggested Filename(s): chararr-pass-an.cpp, cap-an.cpp



Share

Created: 17-Jan-2018 17:00 | Updated: 17-Jan-2018 17:04|