其他分享
首页 > 其他分享> > [leetcode]1108

[leetcode]1108

作者:互联网

C:

错误代码

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

char *defangIPaddr(char *address)
{
    int cnt = 0;
    char tmp[20];
    for (int i = 0; i < strlen(address); i++)
    {
        if (address[i] != '.')
        {
            tmp[cnt] = address[i];
        }
        else
        {
            tmp[cnt] = '[';
            tmp[++cnt] = '.';
            tmp[++cnt] = ']';
        }
        cnt++;
    }
    tmp[cnt] = '\0';
    address = tmp;
    printf("%s\n", tmp);     // 有输出
    printf("%s\n", address); // 有输出
    return address;  
}

int main()
{
    char address[10];
    char *p;
    scanf("%s", address);
    getchar();
    p = defangIPaddr(address);
    printf("%s\n", p); // 无输出
    return 0;
}

正确代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

char *defangIPaddr(char *address)
{
    int length = strlen(address);
    char *str = (char *)malloc(length + 6 + 1);
    int j = 0;
    for (int i = 0; i < length; i++)
    {
        if (address[i] == '.')
        {
            str[j] = '[';
            str[j + 1] = '.';
            str[j + 2] = ']';
            j = j + 3;
        }
        else
        {
            str[j] = address[i];
            j++;
        }
    }
    str[j] = '\0';
    return str;
}

int main()
{
    char address[10];
    char *p;
    scanf("%s", address);
    getchar();
    p = defangIPaddr(address);
    printf("%s\n", p); // 有输出
    return 0;
}

C++:

标签:tmp,cnt,int,char,address,include,leetcode,1108
来源: https://www.cnblogs.com/rootturing/p/14732774.html