看下面代码:
int main()
{
int a[5]={3,6,4,2,5};
char *ptrChar="hello world";//ptrChar是char类型的指针,指向内存空间
int *ptrInt=a;//ptrInt是指向int类型的指针
printf("sizeof(char):%d\n",sizeof(char));
printf("sizeof(int):%d\n",sizeof(int));
printf("sizeof(ptrChar):%d\n",sizeof(ptrChar));
printf("sizeof(ptrInt):%d\n",sizeof(ptrInt));
printf("value of ptrChar is:%d\n",ptrChar);
printf("value of (ptrChar+1) is:%d\n",ptrChar+1);
printf("value of ptrInt is:%d\n",ptrInt);
printf("value of (ptrInt+1) is:%d\n",ptrInt+1);
system("pause");
return 1;
}
程序运行结果如下:
从程序的运行结果可以得出:
指针本身是一个变量,它所存储的是另一个变量的地址,指针变量所占的内存是4个字节,这与它所指向的变量所占的内存空间大小是没有关系的,指针变量本身和它所指向的内存空间是完全独立的。
在源代码级别上对指针变量+1,编译器内部增加的值是该指针所指向的变量的宽度,这种优化避免了指针指向一个不完整的地址。
下面的代码:
void arraySort(int num[5],int lenth)
{
int i,j,temp;
int tmpLenth=sizeof(num)/sizeof(num[0]);
printf("tmpLenth:%d\n",tmpLenth);
for(i=0;i<lenth;i++)
{
for(j=i+1;j<lenth;j++)
{
if(num[i]>num[j])
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
}
}
void displayArray(int num[5],int lenth)
{
int i;
for(i=0;i<lenth;i++)
{
printf("%d\t",num[i]);
}
printf("\n");
}
int main()
{
int a[5]={3,6,4,2,5};
int lenth=sizeof(a)/sizeof(a[0]);//a是数组名,也是数组的首地址,sizeof(a)是整个数组所占的内存空间的大小
printf("lenth:%d\n",lenth);
printf("origin:");
displayArray(a,lenth);
arraySort(a,lenth);
printf("final:");
displayArray(a,lenth);
system("pause");
return 1;
}
运行结果:
这里,数组做函数参数,运行结果发现函数内sizeof(num)/sizeof(num[0])的结果是1,就是说传过来的参数根本不是数组。这里如果真的把数组作为函数参数的话,需要分配临时的栈区执行拷贝等操作,所以编译器对代码进行了优化,把数组退化成了指针,因为指针做函数参数本身就是C语言的精华所在。这里的参数写成num[5],但是编译器在优化的时候会直接忽略中括弧里的数,常见的写法是不写括弧里的数:num[],或者直接写成指针*pNum。