Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
char arrayName[6] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’ }; len = strlen(str1); //total length of str after concatenation
strstr(s1, s2); returns a pointer to the first occurrence of printf(“strlen(str1) : %d\n”, len);
char arrayName[ ] = “Hello”; string s2 in string s1
return 0;
printf(“Greeting message: %s\n”, arrayName); }
Pointers •every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (‘&’
denotes an address in memory) • a pointer is a variable whose value is the address of another variable (direct address of the memory location) • the
actual data type of all pointers regardless of type is a long
Usage
i. define pointer variable
type varName; //pointer declaration • the unary operator ’*’ is used to designate a variable as a pointer
ii. assign the address of a
variable to a pointer
int *integerPointer; integerPointer = &intVar;
double *doublePointer; doublePointer = &doubleVar;
iii. access the value at the
address available in the
float *floatPointer; floatPointer = &floatVar; pointer variable • ‘*’
char *charPointer; charPointer = &charVar; int *myFunction( ) {. . .} // declaring a function returning a pointer returns the value of the
#include <stdio.h> #include <stdio.h>
variable located at the
#include <string.h> address specified by its
const int MAX = 4; operand
OUTPUT:
printf(“Value of *ip variable: %d\n”, *ip); int i=0;
while ( ptrCmp <= &var[MAX-1] ) { double getAverage(int *arr, int size); for (i=0; i<10; i++) {
double getAverage(int *arr, int size) { printf(“*(p + [%d]) : %d\n”, I, *(p+i));
printf(“Address of var[%d] = %x\n”, k, ptrCmp); }
printf(“Value of var[%d] = %d\n”, k, *ptrCmp); int i, sum=0;
ptrCmp++; return 0;
double avg;
k++; }
} //end while loop for pointer comparison for (i=0; i <size; ++i) {
sum += arr[i];
return 0; }
} #include <stdio.h>
avg = (double) sum/size;
int main() {
OUTPUT: OUTPUT: return avg;
Address of var[0] : bf882b30 Address of var[0] : bf882b38 } int balance[5] = {1000, 2, 3, 17, 50};
OUTPUT:
Value of var[0] = 10 Value of var[0] = 200 double avg; Average value is: 214.40000
Address of var[1] : bf882b34 Address of var[1] : bf882b34
Value of var[1] = 100 Value of var[1] = 100 avg = getAverage(balance, 5);
Address of var[2] : bf882b38 Address of var[2] : bf882b30
Value of var[2] = 200 Value of var[2] = 10
printf(“Average value is: %f\n”,
avg);
return 0;
}
Passing pointers to functions in C