数组其实是一种变相的指针,数组名同时也是指针,eg:
CODE == &CODE[0];
数组的加法:
#include<stdio.h>
#define SIZE 4
int main(void)
{
shortdates[SIZE];
short* pti;
shortindex;
doublebills[SIZE];
double* ptf;
pti= dates;//把数组地址付给指针
ptf= bills;
printf("%23s %10s\n", "short","double");
for(index= 0; index < SIZE; index++)
printf("pointers+ %d: %10p %10p\n", index, pti + index, ptf + index);
return0;
}
---------------------------------------------------
short double
pointerrs + 0: 28ff0c 28fee8
pointerrs + 1: 28ff0e 28fef0
pointerrs + 2: 28ff10 28fef8
pointerrs + 3: 28ff12 28ff00
----------------------------------------------------
1. 指针的数值就是它指向的对象的对象的地址
2. 在指针前运用运算符*就可以得到该指针所指向的对象的数值
3. 对指针+1等价于对指针的值加上他所指的对象的字节的大小
Eg:
Dates + 2 == &date[2] //相同的地址
*(dates + 2) == dates[2] //相同的值
总结:可以用指针表示数组的每个元素,并得到每个元素的数值,从本质上说,对同一个对象有两种不同的符号表示方法。
优先级问题:
*的优先级高于+;
所以(*dates) + 2等价于*dates + 2;
函数、数组和指针
int sum(int *ar )
{
inti;
inttaotal = 0;
for(i= 0; i <10; i++)
total+= ar[i];
returntotal;
}
等价于:
int sum(int ar[] )
{
inti;
inttaotal = 0;
for(i= 0; i <10; i++)
total+= ar[i];
returntotal;
}
这段代码说明了:正如可以在指针符号中使用数组名一样,也可以在数组符号中使用指针,
下面代码是对上面的优化,可以灵活的控制变量。
int sum(int * ar, int n)
{
inti;
inttotal = 0;
for(i= 0; i < n; i++)
total+= ar[i];
returntotal;
}
无论在任何形式下,* ar都可以代替ar[];但是ar[]不一定能代替*ar。
数组和指针的不同形式解决同一个问题:
#include<stdio.h>
#define SIZE 10
int sum(int ar[ ], int n)
int main(void)
{
intmarbles[SIZE] = {20, 10, 5, 39, 4, 16, 19, 26, 31, 20};
longanswer;
answer= sum(marbles, SIZE);
printf("thetotal number of marbles is %ld.\n", answer);
printf("thesize of marbles is %u bytes.\n", sizeof marbles);
return0;
}
int sum(int ar[ ], int n)
{
inti;
inttotal = 0;
for(i= 0; i < n; i++)
total+= ar[i];
printf("thesize of ar is %u bytes.\n", sizeof ar);
returntotal;
}
用指针实现:
#include<stdio.h>
#define SIZE 10
int sum(int ar[ ], int n)
int main(void)
{
intmarbles[SIZE] = {20,10, 5, 39, 4, 16, 19, 26, 31, 20};
longanswer;
answer= sum(marbles, marbles + SIZE);
printf("thetotal number of marbles is %ld.\n", answer);
printf("thesize of marbles is %u bytes.\n", sizeof marbles);
return0;
}
int sum(int * start, int * end)
{
inttotal = 0;
while(start< end)
{
total+= *start;
start++;
}
returntotal;
}
关于对++和*运算符优先级的判断:
#include<stdio.h>
int data[2] = {100, 200};
int moredata[2] = {300, 400};
int main(void)
{
int*p1, *p2, *p3;
p1= p2 = data;
p3= moredata;
printf("*p1= %d, *pa = %d, *p3 = %d\n",*p1, *p2, *p3);
printf("*p1++= %d, *++p2 = %d, (*p3)++ = %d\n",*p1++, *++p2, (*p3)++);
printf("*p1 = %d, *p2 = %d, *p3 = %d\n", *p1, *p2, *p3);
return0;
}
--------------------------------------------------------------
*p1 = 100, *pa = 100, *p3 = 300
*p1++ = 100, *++p2 = 200, (*p3)++ = 300
*p1= 200, *p2 = 200, *p3 = 301
---------------------------------------------------------------
*和++具有相同的优先级,只是*是自右向左结合的特性。
C语言学习_数组与指针2