1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
#include <stdio.h> #include <stdlib.h>
#define ROWS 6 #define COLUMNS 5
#define P(a) \ { \ printf("sizeof(%s):\t%d\n",#a, (sizeof((a)))); \ printf("sizeof(%s[0]):\t%d\n",#a,(sizeof((a)[0]))); \ }
#define OUT(a) \ { \ printf("%s:\t addr:%p\n",(#a),(a)); \ for(int i = 0; i < ROWS; i++){ \ printf("%s[%d]:\t addr:%p\n",#a,i,((a)[i])); \ } \ for(int i = 0; i < ROWS; i++){ \ for(int j = 0; j < COLUMNS; j++){ \ printf("%s[%d][%d]: addr:%p\t",(#a),i,j,&a[i][j]);\ } \ printf("\n"); \ } \ }
#define INFO(a) \ { \ P(a) \ OUT(a) \ }
int main(int argc, char *argv[]) { printf("-----二维数组-----\n"); printf("a[%d][%d]\n",ROWS,COLUMNS); char (*a1)[COLUMNS]; a1 = (char(*)[COLUMNS])calloc(ROWS,sizeof(char*)); printf("*****数组指针*****\n"); INFO(a1)
char *a2[ROWS]; for(int i = 0; i < ROWS; i++) { a2[i] = (char*)calloc(COLUMNS, sizeof(char)); } printf("*****指针数组*****\n"); INFO(a2)
char *a3[ROWS]; a3[0] = (char *)calloc(ROWS*COLUMNS, sizeof(char)); for(int i = 1; i < ROWS; i++) { a3[i] = a3[i-1] + COLUMNS; } printf("*****指针数组,一次分配内存*****\n"); INFO(a3)
char **a4; a4 = (char **)calloc(ROWS, sizeof(char*)); for(int i = 0; i < ROWS; i++) { a4[i] = (char*)calloc(COLUMNS, sizeof(char)); } printf("*****两维都未知*****\n"); INFO(a4)
char **a5; a5 = (char**)calloc(ROWS, sizeof(char*)); a5[0] = (char*)calloc(ROWS*COLUMNS, sizeof(char)); for(int i = 1; i < ROWS; i++) { a5[i] = a5[i-1] + COLUMNS; } printf("*****两维都未知,一次分配内存*****\n"); INFO(a5)
free(a1); for(int i = 0; i < ROWS; i++) { free(a2[i]); } free(a3[0]); for(int i = 0; i < ROWS; i++) { free(a4[i]); } free(a4); free(a5[0]); free(a5); return 0; }
|