作为我使用C的家庭作业的一部分,我必须创建一个函数,该函数将一个字符串拆分成以插入的键(即字母)开头的所有单词。除了free函数之外,所有的东西都运行得很好,当我尝试通过函数(行和骨架)释放动态矩阵时,我得到了一个错误,程序已经触发了一个断点。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char **Split(char *str, char letter, int *size);
void free_mat(char **mat, int size);
int main() {
int size, i;
char letter;
char STR[100];
char **strings_arr;
printf("Please enter a string:\n");
flushall;
gets(STR);
printf("Please enter a letter for a check:\n");
letter = getchar();
strings_arr = Split(STR, letter, &size);
if (size > 0) {
printf("The number of words that starts with the letter '%c' in the string '%s' is: %d\n\n", letter, STR, size);
}
printf("The words are:\n");
for (i = 0; i < size; i++) {
printf("%d . %s\n", i+1,strings_arr[i]);
}
free_mat(strings_arr, size);
return 0;
}
void free_mat(char **mat, int size)
{
int i;
for (i = 0; i < size; i++)
{
free(mat[i]);
}
free(mat);
}
char **Split(char *str, char letter, int *size) {
int rows = 0, i, lengh = 0, j = 0, n = 0, m;
char **strings_array;
if ((str[0] == letter) || (str[0] == letter + 32) || str[0] == letter - 32) {
rows++;
}
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ') {
if ((str[i + 1] == letter) || (str[i + 1] == letter + 32) || str[i + 1] == letter - 32) {
rows++;
}
}
}
if (rows == 0) {
printf("There are no words starting with '%c' letter in this string\n\n", letter);
}
i = 0;
strings_array = (char*)malloc(rows * sizeof(char));
if ((str[0] == letter) || (str[0] == letter + 32) || str[0] == letter - 32) {
while (str[i] != ' ' && str[i] != '\0') {
lengh++;
i++;
}
strings_array[j] = (char*)malloc((lengh + 1) * sizeof(char));
for (n = 0; n < lengh; n++) {
strings_array[j][n] = str[n];
}
strings_array[j][n] = '\0';
j++;
}
for (i = 1; str[i] != '\0'; i++) {
if (letter == str[i] || letter == str[i] - 32 || letter == str[i] + 32) {
lengh = 0;
//k = 0;
m = i;
while (str[m] != ' ' && str[m] != '\0') {
lengh++;
m++;
}
strings_array[j] = (char*)malloc(lengh + 1);
for (n = 0; n < lengh; n++) {
strings_array[j][n] = str[i++];
}
strings_array[j][n] = '\0';
j++;
}
}
*size = rows; // sends back the number of words by referance
return strings_array;
}
谢谢!
发布于 2019-05-27 03:12:01
断点是您从IDE或等效工具手动插入到代码中的东西。它用于调试。当您运行代码时,它将在到达断点时停止。因此,只要删除断点,它就会像预期的那样工作。
注意:只删除断点。而不是那一行上的代码。
您在下面的评论中提到您正在使用Visual Studio 2015。下面是该软件中断点的文档:https://docs.microsoft.com/en-us/visualstudio/debugger/using-breakpoints?view=vs-2019
但是关于你的代码还有一些其他的东西。首先,use fgets instead of gets。其次,您可能发布了错误的版本或其他什么,因为free_mat
无法编译。然而,通过将arr
更改为mat
,这个问题很容易解决。
xing在评论中还提到了另一个错误。将strings_array = (char*)malloc(rows * sizeof(char))
更改为strings_array = malloc(rows * sizeof(*strings_array))
。强制转换是不必要的,您为sizeof
的参数选择了错误的类型,如果您传递一个解除引用的指针而不是该类型,您将在将来省去很多问题。
https://stackoverflow.com/questions/56316565
复制相似问题