Skip to content

Latest commit

 

History

History
48 lines (39 loc) · 966 Bytes

ch06指针.md

File metadata and controls

48 lines (39 loc) · 966 Bytes

指针

1、基本概念

int i;
int *pi = &i;
char c;
char *pc = &c;

& 表示取地址运算符
&i 表示取变量i的地址
int *pi = &i 表示定义一个指向int型的指针变量pi并用i的地址来初始化pi
* 表示指针间接寻址运算符
*用在声明中表示声明了一个指针类型 int *pi = &i
*用在表达式中是间接寻址符 *pi = *pi + 1

2、栗子

1、字符串复制strcpy实现

#include <stdio.h>
#include <assert.h>

// 字符串复制
char *str_cpy(char *dst, const char *str)
{
    // 断言,检测传入参数的合法性
    assert((dst != NULL) && (str != NULL));
    // 临时指针
    char *tmp = dst;
    // 这里后面的分号意思是等到括号中条件结束
    while ((*tmp++ = *str++) != '\0');
    return dst;
}

int main(int argc, char const *argv[])
{
    char *str = "hello";
    char new_str[10];
    str_cpy(new_str, str);
    printf("%s\n", new_str);
    return 0;
}