指针、数组

9.7Pointer
  • 指针是一个数值为地址的变量
指针声明
  • 声明指针所指向变量的类型(因为需要知道变量类型所占用的存储空间)
    类型名 +* 指针变量名;
    下图示例,pi 是指针变量名,不是*pi
int * pi;        //*pi 是指向整数变量的指针
char * pc;      //* 与指针名之间空格可选,通常声明时有,指向变量时省略
float * pf,* pg;    //
指针变量赋值
int a=3;
int *p;
p=&a;
  • *”:当后面+指针或地址时,“*”给出存储在被指向地址中的数值
int *p;
//之后若再使用*p,则表示指针p所指变量的值

example: swap3.c

/*swap3.c--使用和指针完成交换*/
#include <stdio.h>
void interchange (int * u, int * v);
int main (void)
{
    int x = 5, y=10;

    printf("Originally x=%d and y=%d.\n", x,y);
    interchange (&x, &y);//向函数传送地址
    printf("Now x=%d and y=%d.\n", x,y);
    return 0;
}

void interchange (int *u, int *v)  
{
    int temp;

    temp = *u;
    *u= *v;
    *v=temp;
}
  • result
    swap3.c

10.3 Pointer and array
  1. the relationship between pointer and array
dates + 2 == &date[2]  //the same station
*(dates + 2) == dates[2]  //the same value
*(dates + i) == dates[i]// 下角标运算和指针运算是等价的
dates + i == &(date+i)
  • an example prove this equalization(example1)
//day_mon3.c   --use pointer//
#include <stdio.h>
#define MONTHS 12

int main (void)
{
    int days[MONTHS] = {31,28,31,30,31,30,31,31,30,31,30,31};
    int index;

    for(index=0; index< MONTHS; index++)
    {
        printf ("Month %d has %d days.\n", index +1, 
        *(days+index)); // == days[index] //prove the relation

    }
    return 0;
}
  • result of example1
[zy111111@cs-linux ~]$ gcc day_mon3.c -o day_mon3
[zy111111@cs-linux ~]$ ./day_mon3
Month 1 has 31 days.
Month 2 has 28 days.
Month 3 has 31 days.
Month 4 has 30 days.
Month 5 has 31 days.
Month 6 has 30 days.
Month 7 has 31 days.
Month 8 has 31 days.
Month 9 has 30 days.
Month 10 has 31 days.
Month 11 has 30 days.
Month 12 has 31 days.
[zy11111@cs-linux ~]$ 

10.4 Function, array and pointer

11.2.2 function gets()

function gets() intergrates with keyboad, stores the char in the array

#include <stdio.h>
#define MAX 81
int main (void)
{
    char name[MAX];
    printf("Hi, what's your name?\n");
    gets(name);    //function gets() intergrates with keyboad, store the char in the array
    printf("Nice name, %s.\n", name);
    return 0;
}
  • result:
    gets() results
12.6 malloc ( ) and free( )
  • 每一个malloc()的调用,应该调用一次free()
  • 头文件应为 stdlib.h

    13 文件的输入和输出
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值