Thursday, 19 February 2015

Passing Pointers to Function In Arduino

i write the same code in three ways..

1. More descriptive way

void setup(){
Serial.begin(9600); // start the serial communication
int a = 2; // initialise the variable
int *a_ptr = &a; // initialise the pointer and assign the variable address to it
addition(a_ptr); // pass the pointer (which holds the address to the function)
Serial.println(*a_ptr); // print the value in the address which the pointer holds
}//end of setup

void loop(){
//do nothing
}//end of loop

//Function definition
void addition(int * a_ptr){ // initializing the passing argument as pointer
*a_ptr = *a_ptr+40; // take the value which is stored in address hold in the pointer and add 40 to it
}//end of addition function


2. Do we have to put the names in function argument as b?
this code is also works same as above

void setup(){
Serial.begin(9600); // start the serial communication
int a = 2; // initialise the variable
int *a_ptr = &a; // initialise the pointer and assign the variable address to it
addition(a_ptr); // pass the pointer (which holds the address to the function)
Serial.println(*a_ptr); // print the value in the address which the pointer holds
}//end of setup

void loop(){
//do nothing
}//end of loop

//Function definition
void addition(int * number){ // initializing the passing argument as pointer
*number = *number+40; // take the value which is stored in address hold in the pointer and add 40 to it
}//end of addition function


3. and One more way to do
avoiding the pointer a_ptr declaration

void setup(){
Serial.begin(9600); // start the serial communication
int a = 2; // initialize the variable a
addition(&a); // pass the address of the variable to the function addition
Serial.println(a); // print the value which is stored in the variable a
}//end of setup

void loop(){
//do nothing
}//end of loop

//addition function declaration
void addition(int * number){
//we pass the address of a variable to the function as argument
// and it is defined as pointer (which is a normal pointer declaration)

*number = *number+40; // we take the value in address and done computation using it.

}

No comments:

Post a Comment