#include <stdio.h> #include <stdlib.h> int main(int argc,char *argv[]) { int num; printf("要輸入的單詞個數:"); scanf("%d",&num); printf("請輸入%d個單詞:",num); char p[num][20]; char ch; int i = 0; int j = 0; ch = getchar(); while((ch=getchar())!='\n') { if(ch==' ') { p[j][i]='\0'; j++; i=0; }else { p[j][i] = ch; p[j][i+1] = '\0'; i++; } } int k; for(k=0;k<num;k++) puts(p[k]); return 0; }
malloc方法:數組
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define SIZE 40 char **mal_ar(int n); int main(void) { int words, i, sum = 0; char **st; printf("您要輸入幾個單詞: "); scanf("%d", &words); getchar(); // 濾掉回車 printf("輸入 %d 個單詞:", words); st = mal_ar(words); printf("下面是您輸入的單詞: \n"); for(i = 0; i < words; i++) { puts(st[i]); sum += strlen(st[i]) + 1; } printf("共佔用%d字節空間\n", sum); free(st); // 釋放指針數組; return 0; } char **mal_ar(int n) { char **pt; char *temp; int len; // 給n個指針分配動態內存空間, 返回指針的指針 pt = (char**)malloc(n * sizeof(char *)); // 臨時數組分配動態內存空間, 返回指針 temp = (char *)malloc(SIZE * sizeof(char)); int i; for(i = 0; i < n; i++) { // 輸入存入臨時數組 scanf("%s", temp); // 測量臨時數組大小,分配正好存放的空間 len = strlen(temp); // 給每一個指針指向的地址分配內存空間 pt[i] = (char *)malloc((len + 1) * sizeof(char)); strcpy(pt[i], temp); } free(temp); return pt; }