功能:在字符串中找出连续最长的数字串,并把这个串的长度返回
函数原型:
unsigned int Continumax(char** pOutputstr, char* intputstr)
输入参数:
char* intputstr 输入字符串
输出参数:
char** pOutputstr: 连续最长的数字串,如果连续最长的数字串的长度为0,应该返回空字符串
pOutputstr 指向的内存应该在函数内用malloc函数申请,由调用处负责释放
返回值:
费了一番周折才了解, *pOutputstr = ""; 这个语句在无形之中修改了指针的指向,使得在调用处 free 的时候指针所指的位置已经不是 malloc 时指针的位置,所以才会出现这种错误。修改之后,正确的代码如下:
函数原型:
unsigned int Continumax(char** pOutputstr, char* intputstr)
输入参数:
char* intputstr 输入字符串
输出参数:
char** pOutputstr: 连续最长的数字串,如果连续最长的数字串的长度为0,应该返回空字符串
pOutputstr 指向的内存应该在函数内用malloc函数申请,由调用处负责释放
返回值:
连续最长的数字串的长度
一开始,我的代码是:
#include <stdlib.h>
#include <oj.h>
unsigned int Continumax(char** pOutputstr, char* intputstr)
{
unsigned int count = 0;
unsigned int temp_count = 0;
int k;
char *p;
char *temp = NULL;
char *temp_out = NULL;
p = intputstr;
*pOutputstr = (char *)malloc(100*sizeof(char));
if(intputstr == NULL || *intputstr == '\0')
{
*pOutputstr = "";
return count;
}
while(*p != '\0')
{
if(*p >= '0' && *p <= '9')
{
temp = p;
while(*p >= '0' && *p <= '9')
{
++temp_count;
++p;
}
}
else
{
if(temp_count >= count)
{
count = temp_count;
temp_out = temp;
}
temp_count = 0;
++p;
}
}
if(temp_count >= count)
{
count = temp_count;
temp_out = temp;
}
for(k = 0; k < count; ++k)
(*pOutputstr)[k] = temp_out[k];
(*pOutputstr)[k] = '\0';
return count;
}
调试时,当测试用例为 NULL 或者 空字符串时总是会出现以下错误(其它测试用例都正常):
费了一番周折才了解, *pOutputstr = ""; 这个语句在无形之中修改了指针的指向,使得在调用处 free 的时候指针所指的位置已经不是 malloc 时指针的位置,所以才会出现这种错误。修改之后,正确的代码如下:
#include <stdlib.h>
#include <oj.h>
unsigned int Continumax(char** pOutputstr, char* intputstr)
{
unsigned int count = 0;
unsigned int temp_count = 0;
int k;
char *p;
char *temp = NULL;
char *temp_out = NULL;
p = intputstr;
*pOutputstr = (char *)malloc(100*sizeof(char));
if(intputstr == NULL || *intputstr == '\0')
{
**pOutputstr = '\0';
return count;
}
while(*p != '\0')
{
if(*p >= '0' && *p <= '9')
{
temp = p;
while(*p >= '0' && *p <= '9')
{
++temp_count;
++p;
}
}
else
{
if(temp_count >= count)
{
count = temp_count;
temp_out = temp;
}
temp_count = 0;
++p;
}
}
if(temp_count >= count)
{
count = temp_count;
temp_out = temp;
}
for(k = 0; k < count; ++k)
(*pOutputstr)[k] = temp_out[k];
(*pOutputstr)[k] = '\0';
return count;
}