- 指针与字符串
%c 打印一个字符,要的是该字符的地址 %s 打印一个字符串,要的是字符串首个字符的地址
int main()
{
char a[] = { "helloworld" };
char *p = a;
printf("%c\n", *(p + 3));
printf("%s\n", p);
printf("%s\n", p + 2);
printf("%d\n", sizeof(p));
printf("%d\n", sizeof(a));
printf("%d\n", strlen(p));
printf("%d\n", strlen(a));
*p = 'm';
printf("%s\n", p);
p++;
*p = 'k';
printf("%s\n", p);
system("pause");
return 0;
}
- 字符指针作为形参
char *my_strcat(char *src,char *dst)
{
int i = 0;
int n = strlen(src);
while (*(dst + i) != '\0')
{
*(src + n + i) = *(dst + i);
i++;
}
*(src + n + i) = '\0';
return src;
}
int main()
{
char str1[128] = "hello";
char str2[128] = "123456";
printf("%s\n", my_strcat(str1, str2));
system("pause");
return 0;
}
- const修饰的指针变量
int main()
{
const int a = 10;
char buf[] = "dfhoiasfdjbklasdnf";
const char *p1 = buf;
p1 = "123456";
char * const p2 = buf;
p2[1] = 'h';
system("pause");
return 0;
}
- 指针字符数组
int main()
{
char *num[3] = { "heihei","haha","xixi" };
for (int i = 0; i < 3; i++)
{
printf("%s\n", num[i]);
}
printf("%c\n", *num[0]);
printf("%c\n", *(num[1] + 1));
printf("%c\n", *(num[2] + 2));
char **p = num;
for (int i = 0; i < 3; i++)
{
printf("%s\n", *(p+i));
}
printf("%c\n", **p);
printf("%c\n", *(*(p+1) + 1));
printf("%c\n", *(*(p+2) + 2));
system("pause");
return 0;
}
字符指针作为main()函数的形参 int argc : 执行可执行程序的参数个数 int *argv[] : 是一个字符指针数组,保存的是参数(字符串)的首元素地址
int main(int argc,int *argv[])
{
printf("%d\n", argc);
printf("%s\n", argv[0]);
printf("%s\n", argv[1]);
system("pause");
return 0;
}
- 字符串处理函数
int main()
{
char p1[128] = "heihei";
char p2[128] = "haha";
strcpy_s(p1,p2);
strncpy_s(p1, p2, 2);
strcat_s(p1, p2);
strncat_s(p1, p2, 3);
strcmp(p1, p2);
strncmp(p1, p2, 3);
int year = 2022;
int month = 4;
int day = 6;
char buf[1024] = "";
int len = sprintf_s(buf, "year=%d month=%d day=%d",year,month,day);
printf("buf[%s]\n", buf);
printf("%d\n", len);
int hour = 0;
int min = 0;
int sec = 0;
char buf2[1024] = "2020:04:06";
sscanf_s(buf2, "%d:%d%:d", &hour, &min, &sec);
printf("%d %d %d\n", hour, min, sec);
system("pause");
return 0;
}
|