【发布时间】:2021-07-23 10:05:50
【问题描述】:
我已经写了一些代码来查找字符串中字符重复的次数。考虑2个指针并动态分配内存,然后将字符串输入其中一个指针。然后将没有冗余的字符复制到另一个指针中最后比较它,增加计数并打印到屏幕上。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void string_cpy(char *from, char *to);
int len(char *p);
int main()
{
char *name, *copy, *hold;
int i, j, lent, count = 0, length;
name = (char *)calloc(25, sizeof(char));
copy = (char *)calloc(25, sizeof(char));
printf("Give a string:");
scanf("%s", name);
puts("");
string_cpy(name, copy);
hold = name;
lent = len(copy); //l=4
length = len(name); //lenght = 5
printf("Characters and their corresponding frequencies\n");
for (i = 0; i < lent; ++i)
{
for (j = 0; j < length;)
{
if (*(copy) == *(name))
{
++count;
++name;
++j;
}
else
{
++j;
++name;
}
}
name = hold;
printf("%c-%d\n", *(copy), count);
count = 0;
++copy;
}
free(name);
free(copy);
return 0;
}
void string_cpy(char *from, char *to)
{
int i, j, k, l, ex;
char key;
l = len(from); //l=5
char *t = to;
for (i = 0, j = 0; i < l; ++i)
{
key = *(from + i);
ex = 0;
for (k = 0; k < i; ++k)
{
if (*(to + k) == key)
{
ex = 1;
}
}
if (!ex)
{ //if(ex==0)
strcpy((to + j), (from + i));
++j;
}
}
}
int len(char *p)
{
int leng = 0;
while (*p != '\0')
{
++leng;
++p;
}
return leng;
}
当我尝试释放()两个指针或 '''char *copy''' 时,它会抛出一个错误
->malloc:对象 0x120e06884 的 *** 错误:未分配被释放的指针
->malloc: *** 在 malloc_error_break 中设置断点进行调试
这是在我的 Mac OS 上完成的
【问题讨论】:
-
例如,您正在更改 main ++name; 中的指针名称。所以在那之后指针不再指向分配的内存。
标签: c