/* Program to demonstrate pointers (strings) Version 1.0 / 2001.09.01. Peter Schindler pstrainer@gmx.net */ #include #include #include /* Declaration of globals *****************************/ void suba (char x[]); void subb (char *px); /* Main program *************************************/ void main (void){ int i; char s[100]; char *ps; // init string for (i=0;i<=100;i++) {s[i]='\0';} printf("Pointer Test Program\n"); printf("Enter a string: "); scanf("%s",&s); printf("\n"); // set pointer ps to the address of s // Mind: ps=s is equivalent to ps=&s[0] // Therefore s[i] is equivalent to *(s+i) // and &s[i] is equivalent to s+i ps=s; // send string (pointer!) to subroutine printf("main01 s=%s ps=%d\n",s,ps); suba(s); printf("main02 s=%s ps=%d\n\n",s,ps); // send pointer to subroutine printf("main03 s=%s ps=%d\n",s,ps); subb(ps); printf("main04 s=%s ps=%d\n\n",s,ps); printf("End of program\n"); _getch(); } /* Get string (pointer) and change it ******************/ void suba (char x[]) { printf("suba01 x=%s\n",x); x[0]='0'; // change to '0' x[1]='1'; // change to '1' printf("suba02 x=%s\n",x); } /* Get pointer to string, change chars *****************/ void subb (char *px) { int i; char c; // print the incoming string printf("subb01 *px="); // warning! this does not work: printf("%s",*px); i=0; c='$'; while (c!='\0') { c=*(px+i++); printf("%c",c); } printf(" px=%d\n",px); // change string *px++='$'; // change to '$' and inc pointer *px--='$'; // change to '$' and dec pointer // print the changed string printf("subb02 *px="); i=0; c='$'; while (c!='\0') { c=*(px+i++); printf("%c",c); } printf(" px=%d\n",px); } /* eof ************************************************/