C/Pointer/Pointer Char

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Assign value to a char pointer

<source lang="cpp">

  1. include <stdio.h>

int main(void) {

 char *p;
 p = "one two three";
 printf(p);
 return 0;

}


      </source>


Assign value to char pointer

<source lang="cpp">

  1. include <stdio.h>

int main(void) {

 char *p, *q;
 printf("Enter a string: ");
 p = gets(q);
 printf(p);
 return 0;

}


      </source>


Char"s pointer"s pointer

<source lang="cpp">

  1. include <stdio.h>

int main(void) {

 char *p, **mp, str[80];
 p = str;
 mp = &p;
 printf("Enter your name: ");
 gets( *mp );
 printf("Hi %s", *mp);
 return 0;

}


      </source>


Get string and assign its value to a char pointer

<source lang="cpp">

int main(void) {

 char *p;
 printf("Enter a string: ");
 gets(p);
 return 0;

}


      </source>


Our own string copy function based on pointer

<source lang="cpp">

  1. include <stdio.h>

void mycpy(char *to, char *from); int main(void) {

 char str[80];
 mycpy(str, "this is a test");
 printf(str);
 return 0;

} void mycpy(char *to, char *from) {

 while(*from) 
     *to++ = *from++;
 
 *to = "\0"; /* null terminates the string */

}


      </source>


Pointer for char, int, float and double

<source lang="cpp">

  1. include <stdio.h>

int main(void) {

 char *cp, ch;
 int  *ip, i;
 float  *fp, f;
 double *dp, d;
 cp = &ch;
 ip = &i;
 fp = &f;
 dp = &d;
 /* print the current values */
 printf("%p %p %p %p\n", cp, ip, fp, dp);
 /* now increment them by one */
 cp++;
 ip++;
 fp++;
 dp++;
 /* print their new values */
 printf("%p %p %p %p\n", cp, ip, fp, dp);
 return 0;

}


      </source>


Read and output: Address pointed by the argument

<source lang="cpp">

  1. include <stdio.h>

int main(void) {

 char *p;
 printf("Enter an address: ");
 scanf("%p", &p);
 printf("Value at location %p is %c\n", p, *p);
 return 0;

}


      </source>


using normal array subscripting

<source lang="cpp">

  1. include <stdio.h>
  2. define ISIZE 10

int main( ) {

char string10[ISIZE];
int i;
for(i = 0; i < ISIZE; i++)
  string10[i]=getchar( );
for(i = ISIZE-1; i >= 0; i--)
  putchar(string10[i]);

}


 </source>


using pointer arithmetic to access elements

<source lang="cpp">

  1. include <stdio.h>
  2. define ISIZE 10

int main( ) {

char string10[ISIZE];
char *pc;
int icount;
pc=string10;
for(icount = 0; icount < ISIZE; icount++) {
  *pc=getchar( );
  pc++;
}
pc=string10 + (ISIZE - 1);
for(icount = 0; icount < ISIZE; icount++) {
  putchar(*pc);
  pc--;
}

}


 </source>


using the strcpy function

<source lang="cpp">

  1. include <iostream>
  2. include <string>

using namespace std;

  1. define iSIZE 20

main( ) {

char s[iSIZE]="Initialized String!",d[iSIZE];
strcpy(d,"String Constant");
cout << "\n" << d;
strcpy(d,s);
cout << "\n" << d;
return(0);

}


 </source>