1.用二级指针
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void func(int **ptr, int row, int col)
{
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
printf("%d\t",ptr[i][j]);
}
printf("\n");
}
}
int main(int argc, char const *argv[])
{
// 数组[]表示数据的个数,总大小是数据个数*类型
int buf[3];// 3*4
// malloc实参是以字节为单位,相当于一维数组
/* int *ptr = malloc(3*sizeof(int));
for(int i = 0; i < 3; i++)
{
ptr[i] = i;
} */
// 将mallc转为二维数组
// 3行
int **ptr1 = (int **)malloc(3*sizeof(int));
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 4; j++)
{
ptr1[i] = (int *)malloc(4*sizeof(int));
}
}
int count = 0;
int i,j;
for(i = 0; i < 3; i++)
{
for(j = 0; j < 4; j++)
{
ptr1[i][j] = ++count;
}
}
func(ptr1,i,j);
free(ptr1);
ptr1 = NULL;
return 0;
}
2.用数组指针
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void func(int (*ptr)[4], int row, int col)
{
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
printf("%d\t",ptr[i][j]);
}
printf("\n");
}
}
int main(int argc, char const *argv[])
{
//定义数组指针,每个指针指向4个元素的首地址
int (*p)[4] =(int (*)[4]) malloc(3*4*sizeof(int));
int count = 0;
int i,j;
for(i = 0;i < 3;i++)
{
for(j = 0;j < 4;j++)
{
p[i][j] = ++count;
}
}
func(p,i,j);
/* for(int i = 0;i <3;i++)
{
for(int j = 0;j < 4;j++)
{
printf("%d\t",p[i][j]);
}
printf("\n");
} */
free(p);
p = NULL;
return 0;
}
3.一级指针
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void func(int *ptr, int row, int col)
{
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
printf("%d\t",ptr[i*4+j]);
}
printf("\n");
}
}
int main(int argc, char const *argv[])
{
int *ptr = (int *)malloc(3*4*sizeof(int));
if(ptr == NULL)
{
//输出失败原因
perror("malloc failed:");
return -1;
}
int i = 0,j = 0,count = 0;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 4; j++)
{
ptr[i*4+j] = ++count;
}
}
func(ptr,3,4);
free(ptr);
ptr = NULL;
return 0;
}