有兩個malloc和free,可看代碼//
///// 代碼不是原創,github下載的別人的。侵權刪
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define SIZE 40
char * * mal_ar(int n);
int main(void)
{
int words, i;
char * * st;
printf("How many words do you wish to enter? ");
scanf_s("%d", &words);
getchar(); //濾掉回車
printf("Enter %d words now:\n", words);
st = mal_ar(words);
printf("Here are your words:\n");
for (i = 0; i < words; i++)
{
puts(st[i]);
free(st[i]); //釋放每個指針指向的內存
}
free(st); //釋放指針數組
return 0;
}
char * * mal_ar(int n)
{
char * * pt;
int i, j;
char ch;
//給n個指針分配動態內存空間,返回指針的指針
pt = (char * *)malloc(n * sizeof(char *));
for (i = 0; i < n; i++)
{
//給每個指針指向的地址分配內存空間
pt[i] = (char *)malloc(SIZE * sizeof(char));
//可以僅用scanf("%s", pt[i]);
while (isspace(ch = getchar())) //處理單詞之前的空格符
continue;
pt[i][0] = ch; //單詞首字符
j = 1;
while (!isspace(pt[i][j] = getchar()))
j++;
pt[i][j] = '\0'; //將末尾的空格替換爲\0'
}
return pt;
}
對理解指針和字符串的含義有意義
2020-04-10
大連