创建动态数组,里面存放键盘输入的数字,回车键确定输入,-1为退出条件。
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { int count = 0; int *p = NULL; int *prev = NULL; int new; int i; while (1) { printf("input number \n"); scanf("%d", &new); if (-1 == new) break; prev = p; p = (int *)malloc(sizeof(int) * (count + 1)); if (NULL == p) { perror("malloc"); if (prev) free(prev); return -1; } if (prev) { memcpy(p, prev, sizeof(int) * count); free(prev); } p[count] = new; count++; } for (i = 0; i < count; i++) printf("p[%d] = %d\n", i, p[i]); free(p); return 0; }