一、指针
1.指针概念
#include <stdio.h>
int main()
{
printf("%d\n", sizeof(int *)); //所有指针类型都占4个字节
printf("%d\n", sizeof(char *));
printf("%d\n", sizeof(double *));
int a = 1;
int *p = &a; //指针p指向a
*p = 100; //a = 100; *取值
printf("a = %d\n", a);
char ch = 'a';
char *q = &ch;
*q = 'b';
printf("%c\n", ch);
//p = &ch; //类型不兼容
printf("p的地址:%p\n", p);
printf("q的地址:%p\n", q);
printf("p+1的地址:%p\n", p + 1);
printf("q+1的地址:%p\n", q + 1); //char *和int *步长不一样,char *加1,地址增加1个字节,int *加1,地址增加4字节
return 0;
}
2.strcpy
#include <stdio.h>
void mystrcpy(char *dest, char *src)
{
/*while (*src != '\0')
{
*dest = *src;
src++;
dest++;
}*/
while ((*dest++ = *src++) != '\0'); //1、取值 2、赋值 3、判断 4、移动指针
}
int main()
{
char a[32] = "12345";
char str[32] = "helloworld";
char ptr[32] = {0};
mystrcpy(ptr, str);
printf("%s\n", ptr);
mystrcpy(str, a);
printf("%s\n", str);
return 0;
}
3.指针使用步骤
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p; //1、定义指针
//p = 0x100; //段错误:访问了不能访问的内存 不能自己指定地址
//*p = 1;
int a; //操作系统分配的空间,合法的
p = &a; //2、给指针赋值 地址合法
*p = 1;
int *q; //q是局部变量,未初始化的局部变量是垃圾值 野指针 不能使用
//*q = 100;
int *z = NULL; //空指针 空指针也是不能使用
//*z = 100; //段错误
int *pa = (int *)malloc(sizeof(int) * 2); //申请空间(堆空间) malloc返回值是void * 所以需要强转
if (NULL == pa) //申请失败,返回NULL
{
printf("malloc failure!\n");
}
*pa = 100;
*(pa + 1) = 200;
int i;
for (i = 0; i < 2; i++)
{
printf("%d ", pa[i]);
}
printf("\n");
return 0;
}
4.指针和数组
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int a[5] = {1, 2, 3, 4, 5};
int *p = a; //赋值合法
int i;
for (i = 0; i < sizeof(a) / sizeof(a[0]); i++)
{
//printf("%d ", a[i]); //下标法访问数组元素
//printf("%d ", *(p + i)); //指针法访问数组元素
printf("%d ", *(a + i));
}
printf("\n");
char *ptr = (char *)malloc(sizeof(char) * 32);
strcpy(ptr, "helloworld");
//printf("%s\n", ptr);
for (i = 0; i < 10; i++)
{
printf("%c", ptr[i]);
}
printf("\n");
return 0;
}
5.字符串插入
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#if 0
int main()
{
char str[32] = {0};
int num, i;
char ch;
printf("Please input...\n");
scanf("%s%d %c", str, &num, &ch);
int length = strlen(str);
for (i = 0; i < length - num + 1; i++)
{
str[length - i] = str[length - 1 - i];
}
str[num - 1] = ch;
printf("%s\n", str);
return 0;
}
#endif
int main()
{
char *ptr = (char *)malloc(sizeof(char) * 32);
int num, i;
char ch;
scanf("%s%d %c", ptr, &num, &ch);
int length = strlen(ptr);
for (i = 0; i < length - num + 1; i++)
{
*(ptr + length - i) = *(ptr + length - 1 - i);
}
*(ptr + num - 1) = ch;
printf("%s\n", ptr);
return 0;
}
6.指针数组
#include <stdio.h>
int main()
{
int a[10];
char *str[] = {"hello", "world"};
printf("%s\n", *str);
printf("%s\n", *(str + 1));
printf("%s\n", str[0]);
printf("%s\n", str[1]);
return 0;
}