标签:input amp 形参 numbers cat 两种 mil inpu oca
要实现指针作为函数形参,改变实参指针的值。一般有两种做法:
接上篇:为一个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); Output(pointer_counterpart, m, n); free(pointer_counterpart); return 0; } void Input(int *pointer_1, int *pointer_2) { printf ("Please input the line & column:\n"); scanf ("%d%d", pointer_1, pointer_2); } int *allocation(int dimention) { int *pointer; printf ("Please input %d numbers:\n", dimention); pointer = (int*)malloc(dimention * sizeof(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:\n"); for (int i = 0; i < line; ++i) { for (int j = 0; j < column; ++j) { printf ("%d ", *pointer_copy++); //这种表达方式很好 } printf ("\n"); } 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:\n"); 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:\n"); for (int i = 0; i < line; ++i) { for (int j = 0; j < column; ++j) { printf ("%d ", *(pointer[i] + j)); } printf ("\n"); } } void free_pointer(int **pointer, int line) { for (int i = 0; i < line; ++i) { free(pointer[i]); } }
标签:input amp 形参 numbers cat 两种 mil inpu oca
原文地址:http://www.cnblogs.com/gzl0928/p/7765974.html