要实现指针作为函数形参,改变实参指针的值。一般有两种做法:
- 使用双指针,或者指针数组形式作为形参,将实参的地址传入函数,也即要给形参传入指针的地址!
- 利用返回指针的函数直接返回分配好内存的地址(动态(堆)内存分配你懂的)
接上篇:为一个m行n列的二维数组开辟空间输入各元素的值,再然后输出。
方法一:直接分配一块连续的空间存放m * n个元素:
#include <stdio.h> #include <stdlib.h> #include <memory.h> int main() { void Input(int *pointer_1, int *pointer_2); //输入行列 int *allocation(int dimention); //分配内存 void Output(int *pointer, int line, int column); //输出各元素值 int m, n; int *pointer_counterpart; Input(&m, &n); pointer_counterpart = allocation(m * n); //感觉还是要仔细,小错误很耽误事儿。例如pointer_counterpart = *allcation(m * n) Output(pointer_counterpart, m, n); free(pointer_counterpart); return 0; } void Input(int *pointer_1, int *pointer_2) { printf ("Please input the line & column: "); scanf ("%d%d", pointer_1, pointer_2); } int *allocation(int dimention) { int *pointer; printf ("Please input %d numbers: ", dimention); pointer = (int*)malloc(dimention * sizeof(int)); //分配了一块连续的空间,小细节要注意的点,强制类型转换(int *) memset(pointer, 0, dimention); for (int i = 0; i < dimention; ++i) { scanf ("%d", pointer + i); } return pointer; } void Output(int *pointer, int line, int column) { int *pointer_copy; pointer_copy = pointer; printf ("The matrix is: "); for (int i = 0; i < line; ++i) { for (int j = 0; j < column; ++j) { printf ("%d ", *pointer_copy++); //这种表达方式很好 } printf (" "); } pointer_copy = pointer; }
方法二:连续分配m块连续的空间各存放 n个元素:
#include <stdio.h> #include <stdlib.h> int **pointer_counterpart; //要定义此全局变量 int main() { void Input(int *pointer_1, int *pointer_2); void allocation(int line, int column); void display(int **pointer, int line, int column); void free_pointer(int **pointer, int line); int m, n; //int *pointer_counterpart[line]; Input(&m, &n); allocation(m, n); display(pointer_counterpart, m, n); free_pointer(pointer_counterpart, m); //pointer_counterpart = return 0; } void Input(int *pointer_1, int *pointer_2) { printf ("Please input the line & column: "); scanf ("%d%d", pointer_1, pointer_2); } void allocation(int line, int column) { //int **pointer; ///二重指针多与指针数组一同使用 int *pointer_array[line]; for (int i = 0; i < line; ++i) { pointer_array[i] = (int*)malloc(column * sizeof(int)); } printf ("Please input %d *%d numbers:", line, column); for (int i = 0; i < line; ++i) { for (int j = 0; j < column; ++j) { scanf ("%d", pointer_array[i] + j); } } //pointer = pointer_array; pointer_counterpart = pointer_array; ///全局变量指针指向了指针数组的首地址 } void display(int **pointer, int line, int column) { printf ("The matrix is: "); for (int i = 0; i < line; ++i) { for (int j = 0; j < column; ++j) { printf ("%d ", *(pointer[i] + j)); } printf (" "); } } void free_pointer(int **pointer, int line) { for (int i = 0; i < line; ++i) { free(pointer[i]); } }