创建二级指针动态数组,模拟指针数组。里面存放键盘输入的字符串,回车键确定输入,-1为退出条件。
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char **p = NULL; char **prev = NULL; int count = 0; char buf[1024] = {0}; int i; int val; while (1) { printf("input string\n"); scanf("%s", buf); if (!strncmp("-1",buf, 2)) break; prev = p; p = (char **)malloc((count + 1) *sizeof(char *)); if (NULL == p) { free(prev); val = -1; goto err1; } memcpy(p, prev, count * sizeof(char *)); free(prev); p[count] = (char *)malloc(strlen(buf) + 1); if (NULL == p[count]) { val = -1; goto err2; } memcpy(p[count], buf, strlen(buf) + 1); count++; } val = 0; for(i = 0; i < count; i++) printf("p[%d] = %s\n", i, p[i]); err2: free(p); err1: for(i = 0; i < count; i++) free(p[i]); return val; }