【发布时间】:2017-11-11 23:30:38
【问题描述】:
我遇到问题的函数是我在下面创建的,DynamicString。 该函数旨在创建一个可变大小的字符串。
void DynamicString(char **txt)
{
int i;
int n = 0; //number of characters
char c;
*txt = (char *)malloc(1);//one byte of memory for the terminator
(*txt)[0] = '0'; // termination charcter is the first point
char *tmp = NULL; //temporary pointer
scanf("%c", &c);
while(c != '\n')//while true input
{
tmp = (char*)malloc(n+2);//allocates memory for incoming charcter and termination point
for (i=0; i < n; ++i)//doesn't copy over an empty list
{tmp[i] = (*txt)[i];}
tmp[n] = c; //inputs character in releveant position
tmp[n+1] = '0'; //places term. point
++n;// incriments the number of charcters(not including 0
scanf("%c", &c);
}
free(*txt);//frees old mem
*txt = tmp;// txt points to tmp
printf("\nThe entered string is : %s",*txt);
return;
}
void Frequency(char *s, int *array)
{
int i;
for(i=0; s[i] != '\0'; i++)//counts the frequncies of each character
{
array[s[i]]++;
}
/* Print characters and their frequency */
return;
}
int main()
{
//int Freq[128] = {0};// frequency of characters
char * string;
DynamicString(&string);
free(string);
return 0;
}
如果有人可以修复我已经创建的代码,那将非常有帮助。我知道可能有更好的算法,但我只想知道我做错了什么。谢谢!
【问题讨论】:
-
代码看起来很奇怪,问题之一是字符串终止符号不正确。它应该是“\0”,而不是“0”。
-
我认为你所有的
'0'字符都应该是'\0',这是完全不同的。 (我看到两个'0'实例和一个'\0'实例) -
遗憾的是没有变化
-
问题是我没有在 while 循环中复制 tmp 字符串。
标签: c