#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
#if 0 //条件编译1
int *p; //定义一个指针
printf("%p\n", p);
*p = 1; //不合法 不能直接使用
int a = 1;
int *q;
q = &a; //给指针赋值
int *pa;
pa = q; //给pa赋值q
#endif
char *fp;
fp = (char *)malloc(sizeof(char) * 20);
//向操作系统申请空间 连续的空间 堆空间
if (NULL == fp)
{
printf("malloc falure!\n");
}
strcpy(fp, "helloworld");
printf("%s\n", fp);
free(fp); //malloc申请的空间不用后释放空间
return 0;
}
#include <stdio.h>
int main()
{
int i;
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; //数组名a 常指针
int *p = a; //指针p指向数组的第一个元素
for (i = 0; i < 10; i++)
{
//printf("%d ", a[i]); //下标法
//printf("%d ", *(a + i)); //指针法
printf("%d ", *(p + i)); //指针法
}
printf("\n");
char *q = "helloworld"; //通过数组下标访问指针 就存储空间不一样
for (i = 0; i < 10; i++)
{
printf("%c", q[i]);
}
printf("\n");
return 0;
}
#include<stdio.h>
int main()
{
char *str[] = {"I love China", "hello", "Nice"}; //指针数组
//[]优先级高,str[],所以是数组
//I love China 是指针 指向字符串 I love China
printf("%s\n", str[0]);
printf("%s\n", str[1]);
printf("%s\n", str[2]);
//打印字符串 %s 参数:字符串的首地址
printf("%s\n", str);
return 0;
}
#include <stdio.h>
int main()
{
char *ptr = "helloworld"; //ptr指向hellworld字符串
char *str;
str = "helloworld"; //同上
char a[20] = "helloworld"; //数组a保存helloworld字符串
char b[20];
//b = "hellowrold"; //错误 b数组名是常指针
strcpy(b, "helloworld"); //正确
return 0;
}
#include <stdio.h>
void print()
{
printf("helloworld\n");
}
int add(int x, int y)
{
return (x + y);
}
int main()
{
void (*p)(); //函数指针 指向一个没有形参、没有返回值的函数
p = print;
//print();
p();
int (*q)(int, int);
q = add;
q(1, 2);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *Init() //指针函数
{
char *tmp = (char *)malloc(sizeof(char) * 10);
return tmp;
}
int main()
{
char *str;
str = Init();
strcpy(str, "hello");
return 0;
}