#include <stdio.h>
#include <stdlib.h>
int main(){
int i;
char **arr;
arr = malloc(sizeof(char*) * 5);//for 5 string
for(i=0;i<5;++i){
arr[i] = malloc(sizeof(char) * 10);//reserved storage space length 9
scanf("%9[^\n]%*c", arr[i]);//Read until \n, and discard \n
}
printf("\n");
//check print and free
for(i=0;i<5;++i){
puts(arr[i]);
free(arr[i]);
}
free(arr);
return 0;
}
int i, n;
char **arr;
arr = malloc(sizeof(char*) * 5);
for(i=0;i<5;++i){
arr[i] = malloc(sizeof(char) * 10);
}
i=0;
while(i<5 && 1==scanf("%9[^\n]%*c", arr[i]))
++i;
n = i;
printf("\n");
//check print
for(i=0;i<n;++i){
puts(arr[i]);
}
//deallocate
for(i=0;i<5;++i)
free(arr[i]);
free(arr);
你不需要投。爲什麼不檢查分配內存的溢出?關於如何從一開始就讀取輸入的數據或釋放內存的想法? – 2014-12-06 09:28:36