第十章 再论指针
1,数组char a;访问元素a;
编译器符号列表中,a的地址9980
(1)取i的值,乘以行宽row,加到9980上. 9980+i*row;
(2)取j的值,乘以元素factor的宽度,9980+i*row+j*factor;
(3)从地址(9980+i*row+j*factor)中取出内容.
2,数组char* a6];
访问元素a;
编译器符号列表中,a的地址9980
(1)取i的值,乘以4,加到9980上. 9980+i*4;
(2)取j的值,乘以元素factor的宽度,9980+i*4+j*factor;
(3)从地址(9980+i*4+j*factor)中取出内容.
3,使用指针从函数返回一个数组.
实例代码:
#include <stdio.h>#include <malloc.h>int( *getPF() ){ int (*p); p=calloc(20,sizeof(int)); return p;}int main(){ int (*p); p=getPF(); printf("%d\n",*(*p+2));return 0;}
4,动态分配
#include <stdio.h>#include <stdlib.h>#include <malloc.h>int current_element=0;int total_element=32;char* dynamic;;void add_element(char c){ if(current_element==total_element-1) { total_element*=2; dynamic=(char*)realloc(dynamic,total_element); if(dynamic==NULL) printf("Couldn't expand the table.\n"); } current_element++; dynamic=c;}int main(){ int i; dynamic=(char*)malloc(total_element); for(i=1;i<128;i++) add_element(i); for(i=1;i<128;i++) printf("%c ",dynamic); free(dynamic);return 0;}
页:
[1]