我编写了一个函数,该函数应该接收一个字符串和一个字母,如果字母是单词的第一个字母,我应该将其插入动态分配的字符串中。问题是当我尝试释放分配的字符串数组时,有什么建议吗?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char **split(char *string, char letter, int *size);
void printmatrix(char **str, int size);
void free_matrix(char **p, int size);
void main() {
char str[] ="Rony Goodman got a good mark";
char ch,**p;
int size;
printf("Enter a small letter you are looking for:");
scanf("%c", &ch);
rewind(stdin);
p=split(str, ch,&size);
free_matrix(p, size);
getch();
}
char ** split(char *string, char letter, int *size) {
int count = 0, i = 0,num_of_words=0,j=0,t=0;
char **str_arr;
char *token;
const char s[2] = { ' ' };
token = strtok(string, s);
if (token != NULL && tolower(token[0]) == letter) {
count++;
num_of_words++;
}
else {
num_of_words++;
}
while (token != NULL) {
token = strtok(NULL, s);
if (token!=NULL && tolower(token[0]) == letter) {
count++;
}
else {
num_of_words++;
}
}
//now we have the amount of the words inside the string;
str_arr = (char**)malloc(sizeof(char*)*count);
token = strtok(string, s);
if (tolower(token) == letter) {
str_arr[j] = (char*)malloc(strlen(token) * sizeof(char));
strcpy(str_arr[j], token);
j++;
}
while(i<num_of_words){
token += strlen(token) + 1;
if (tolower(token[0]) == letter) {
str_arr[j] = (char*)malloc(strlen(token) * sizeof(char));
strcpy(str_arr[j], token);
j++;
i++;
}
else {
i++;
}
}
*size = count;
return str_arr;
}
void free_matrix(char **p,int size){
int i;
for (i = 0; i < size; i++) {
free(p[i]);
}
free(p);
}
由于某种原因,当我进入free(p [i])...行时,什么也没发生。