程序源自《C指针:基本概念核心技术及最佳实践》第四章的字符串数组一节
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void freestrmemory(char** arr, int length);
int main(int argc, char* argv[])
{
char** arr = NULL;
char tempstring[30];
int i;
for(i = 0 ; i< 6; i++)
{
printf("Insert data\n");
scanf("%s",tempstring);
if(arr == NULL)
{
arr = (char**)malloc(sizeof(char*));
}
else
{
arr = (char**)realloc(arr, sizeof(char*)*(i+1));
}
arr[i] = (char*)malloc(sizeof(char)*(strlen(tempstring) + 1));
strcpy(arr[i], tempstring);
}
for(i = 0; i< 6; i++)
{
printf(" %d - %s\n", i, arr[i]);
}
freestrmemory(arr, 5);
return 0;
}
void freestrmemory(char** arr, int length)
{
int i;
for( i = 0; i<=length; i++)
{
free(arr[i]);
}
free(arr);
}
运行结果如下:
Administrator@PC-20150
# String12.exe
Insert data
lkf
Insert data
kjkjk
Insert data
ddsdds
Insert data
d
Insert data
sdsd
Insert data
dsd
0 - lkf
1 - kjkjk
2 - ddsdds
3 - d
4 - sdsd
5 - dsd