C/Pointer/Pointer Char
Содержание
- 1 Assign value to a char pointer
- 2 Assign value to char pointer
- 3 Char"s pointer"s pointer
- 4 Get string and assign its value to a char pointer
- 5 Our own string copy function based on pointer
- 6 Pointer for char, int, float and double
- 7 Read and output: Address pointed by the argument
- 8 using normal array subscripting
- 9 using pointer arithmetic to access elements
- 10 using the strcpy function
Assign value to a char pointer
#include <stdio.h>
int main(void)
{
char *p;
p = "one two three";
printf(p);
return 0;
}
Assign value to char pointer
#include <stdio.h>
int main(void)
{
char *p, *q;
printf("Enter a string: ");
p = gets(q);
printf(p);
return 0;
}
Char"s pointer"s pointer
#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;
}
Get string and assign its value to a char pointer
int main(void)
{
char *p;
printf("Enter a string: ");
gets(p);
return 0;
}
Our own string copy function based on pointer
#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 */
}
Pointer for char, int, float and double
#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;
}
Read and output: Address pointed by the argument
#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;
}
using normal array subscripting
#include <stdio.h>
#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]);
}
using pointer arithmetic to access elements
#include <stdio.h>
#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--;
}
}
using the strcpy function
#include <iostream>
#include <string>
using namespace std;
#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);
}