A local variable containing an address by using this

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: i++) sum += *(px+i); sum += x[i]; 18 Pointers and Arrays (cont’d) Recall that the name of an array is the address of the iniCal element of the array. • Thus these two assignments are equivalent: – py = &y[0]; py = y; However, there is one difference between a pointer (py) and an array name (y): • – A pointer is a variable, thus py++ and py = y are legal statements – An array name is not a variable, thus y++ and y = py are illegal statements 19 Pointers and Arrays (cont’d) • When we pass an array name to a funcCon, we are passing the memory locaCon of the iniCal element (passing by reference) – Within the invoked funcCon, this argument is a local variable. A local variable containing an address. • By using this local variable (the address) we may manipulate the contents of the memory using indirecCon. • Because the address variable is local to the funcCon, it can be manipulated without affecCng the memory 20 Pointers and Arrays (cont’d) • Example: /* charfind: return the position of an char in an array of char*/ int charfind(char *ptr, char c, int num) { int n; for (n=0;((*ptr != c)&&(n < num)); ptr++) n++; return(n); } Since ptr is a pointer, we may increment it, and doing so will have no effect on our array because we are only incremenCng our local copy of the pointer variable. 21 Pointers and Arrays (cont’d) • As a formal parameter in a funcCon definiCon, char s; and char *s; are equivalent. However, when using an array the former is normally preferred because it explicitly indicates you are using an array. 22 Example of Pointer Use #include<stdio.h> void cubebyref(int *nptr); /*function prototype*/ int main() { int number = 5; /*initialize number...
View Full Document

Ask a homework question - tutors are online