MAKAUT BTech CSE/IT Data Structure concepts

Answer:

Accessing some memory locations remotely:

A pointer variable may be used to access some memory location that has been allocated for some other variable within or outside of its scope.

The variables defined within a function (remember, main() is also a function), are alive and active within the function itself. The code within which a variable is alive is called the scope of the variable. Thus all variables created within a function (including the formal parameters) have local or function level scope. 

The local variable of one function can not be accessed from other functions by its name. But, we can access the memory location allocated for that variable using its address. Hence, we may use a pointer variable to access the local variable of some function from another function, if needed. This concept can be further applied to parameter passing while function calls, File Handling, the creation of Linked Lists, Trees, and many more problem domains.

Explanation

A variable.

Example:

The following code snippet shows how to use a pointer.

#include<stdio.h>

void print_x(int x){   // This function creates a new variable named x  
    x = 200; 
    printf("\n\nvalue of x is %d", x);
}

void print_x_using_pointer(int *p){
    printf("\n\nvalue of x is %d", *p);
}

int main(){
    int x = 100;
  
    print_x();  // This will print 200    
    print_x_using_pointer(int *p);  // This will print 100   
    
    return 0;
}

Related Question:

  1. What is “call by reference” in C language?
  2. What is the scope of any variable?
  3. What are the “actual parameter” and the “formal parameter”?
  4. What is the scope of the formal parameters?

0 Replies to “How pointers are used in Parameter Passing in C?

Leave a Reply

Your email address will not be published. Required fields are marked *