Pointers - 12 Pointers & functions - Passing String, Structure to a functions

Passing String, Structure to a functions

Passing String to a function :-

Similar to passing array to a function using pointer, strings can also be passed to function using pointers.

We will see an example to pass strings to function using pointer.

/* Program to convert a string to uppercase */

#include < stdio.h >
#include < ctype.h >
Converttouppercase( char *p )
{
while( *p != '\0' )
    {
       printf ( "%c", toupper( *p ) );
       p++;
     }
}

main ( )
{
char word [ 30 ];

printf ( "\n Enter any word " );
scanf ( "%s", word );

Converttouppercase ( word );

}


           In the above program, in the main a string will be accepted as input and will be stored in 'word'. Then we are calling a function "Converttouppercase(word);". Address of first character of string word is passed as an argument to this function. Function definition of Converttouppercase() a pointer to char variable p(formal argument ) receives the address of first character of a string word (actual argument). Character by character will be accessed in while loop until a null character appears. Each character printed in uppercase using toupper() function belong ctype.h .


Passing Structure to a function :-


Even structure can be passed to function and in the function definition through pointer to structure. We will see through an example.

#include < stdio.h >
struct student 
{
int rno;
char name[30];
};

SRead(struct student *p)
{
printf(" \n Enter the rno and name " );
scanf ( "%d%s", p -> rno, p -> name);
}
SPrint(struct student *p)
{
printf(" \n Rno = %d ", p -> rno);
printf(" \n Name = %s ", p -> name);
}

main()
{

struct student s1;

SRead ( s1 );

SPrint ( s1 );

}

In the above program address of structure variable s1 is sent to function SRead() and SPrint() and it is received by pointer to structure variable p. Members of structure are accessed using an operator ->.

Comments