1

此程序应将 n't 后跟字母更改为“not”。喜欢不要->不要。但它显示了一些非常奇怪的输出。例如,如果我只是跳过打印字符串长度输出是垃圾。我也不能说空间如何在输出中变为 s2ace。如果我不知道更好,我会说我在代码中有一个幽灵。

#include<stdio.h>
#include<string.h>
#include<ctype.h>

int func(char **str, int cur_len, int max_len)
{
    if (cur_len <= 3)
        return(cur_len);
    else if(max_len < cur_len)
        return(-1);

    int i,j;
    char new[max_len];
    new[0]='\0';
    char temp[2];

    for (i = 0; i < cur_len; i++)
    {
        if(i > 0 && i < cur_len - 2 && isalpha((*str)[i-1]) && (*str)[i] == 'n' && (*str)[i+1] == '\'' && (*str)[i+2] == 't')
        {
            strcat(new," not");
            i=i+2;
        }
            else
        {
            temp[0]=(*str)[i];
            temp[1]='\0';
            strcat(new, temp);
        }
    }
    j = strlen(new);
    if (j > max_len)
        return(-1);

    *str = new;
    return(j);

}


int main()
{
    char *x = "Please don't do anything stupid. all the n't followed by an alphabate should be changed to not followed by a space. e.g. doesn't.";
    int len, max, result;
    len = strlen(x);
    printf("String size = %d\n",len);//**if i comment this line all output goes down the drain.**
    max = 200;

    result = func (&x, len, max);
    if(result == -1)
    {
        printf("No change possible\n");
        return(-1);
    }
    printf("No of changes = %d\n",strlen(x)-len);
    printf("New String is :: %s\n",x);//**how does space change into s2ace??**
    return(0);
}

输出是

129No of changes = 2 New String is :: 请不要做任何愚蠢的事情。所有不跟随字母的 n 都应更改为不跟随 s2ace。例如没有。

4

1 回答 1

0

通过替换为以最少的代码更改来解决char new[max_len];问题

char *new = *str = (char*)malloc(max_len+1);

您还需要#include <stdlib.h>在顶部添加。

正如评论中提到的,一旦函数返回,指向本地对象(具有自动存储类)的指针就会变得无效。

静态对象不会消失,但我不相信可变长度数组是静态的。所以,你被 malloc/calloc 困住了。

请务必记录此行为,以便调用函数的作者知道在不再需要内存时释放指针。(如果您要狡辩说您是作者并且已经知道它,我会指出它可以帮助您的代码的读者了解发生了什么。)

于 2013-09-22T21:43:52.580 回答