Thursday 8 June 2023

Pointers and Functions in C

What are Pointers and Functions in C?

The difference of opinion to the functions can be passed in two ways –

1.       Call by Value

2.       Call by Address

In call by value, only the values of arguments are sent to the function while in call by remark about, mark of arguments are sent to the purpose. In call by value procedure, any interchange made to the formal reasoning will not throw back on the real arguments.

Pointers in c language, Function in C language, call by value
Pointers and Functions in C language image-1

C uses only call by value when progress arguments to a function, but we can reproduce call by address by using pointers.

Here a and b are variables announced in the function main() while x and y are announced in the function value(). These an element resides at different addresses in store. Whenever the function value() is called, two variables are produce named x and y and are set to the value with the values of variables a and b.

This type of a limit going past is called call by value since we are only provide the values of real arguments to the calling function. Any working performed on variables x and y in the function value(), will not affect variables a and b.

Even though C does not use call by address, but we can reproduce it by passing addresses of variables as arguments to the function. To receive the addresses internal the function, we will need pointer variables.

Here we are progress mark of variables a and b in the function call. So the be given formal arguments in the function statement should be announced of pointer type. Whenever function ref() is called, two pointer to int variables, named p and q, we will be able to entrance variables a and b from function ref().

1.1   Function returning Pointer

We can have a function that come back a pointer. The syntax of statement of such type of function is –

Type *func(typ1, type2,…….);

While go back a pointer, make sure that the reminder address go back by the pointer will exist even after the the physical end of something of function.

Here we are come back a pointer which points to a regional variable. We know that a local variable live only inside the function. Take for granted the variable x is stored at address 2500, so the value of p will be 2500 and this value will be go back by the function func(). As soon as func() terminates, the local variable x will cause to live.

The address come back or returned by func() is allot or assigned to pointer variable ptr inside main(), so now ptr will carry or contain address 2500. When we dereference or obtain the address of a data item held in another location from ptr, we are the action or typing to entry or access the value of a variable that no longer exists. So never or at no time go back or return a pointer that point to a local variable.


Computer stuff kit tricks of Topics 52.