0
Follow
0
View

Runs successfully, but displays an error.

wang___dan 注册会员
2023-02-27 14:52

if(m[i] == 'd' & & m[i + 1] == 'o' & & m[i + 2] == 't' & & i < 998 & & m[i + 3] ! = ")

if(i < 997 & & m[i] == 'd' & & m[i + 1] == 'o' & & m[i + 2] == 't' & & m[i + 3] ! = ' ')


if(m[i] == 'a' & & m[i + 1] == 't' & & a & & m[i + 2] ! = ")

if(i < 998 & & m[i] == 'a' & & m[i + 1] == 't' & & a & & m[i + 2] ! = ' ')

koxingchen 注册会员
2023-02-27 14:52

This answer quotes ChatGPT

The reason this code might work fine locally but fail online is that it uses Pointers to return the address of a local variable. In the solution function, it points char* result to the first address of char m[] and returns result. However, when the solution function exits, the memory space pointed to by m is freed, so the memory space pointed to by result is now undefined. This can lead to errors on some platforms.

To solve this problem, you can define a character array char result[1000] in the main function and pass it as an argument to the solution function. Modify the result array in the solution function, not the m array. This way, when the solution function exits, the result array is still defined and accessible in the main function.

Here is an example of the modified code:

#include 
#include 

void solution(char m[], char result[]) {
    int i, p;
    int a = 1;
    for (i = 1; i <= 998; i++) {
        if (i > 1) {
            if (m[i] == 'd' && m[i + 1] == 'o' && m[i + 2] == 't' && i < 998 && m[i + 3] != ' ') {
                result[i - 1] = '.';
                for (p = i + 1; p < 998; p++)
                    result[p - 1] = m[p + 1];
                result[p - 1] = ' ';
                result[p] = '\0';
            }
            if (m[i] == 'a' && m[i + 1] == 't' && a && m[i + 2] != ' ') {
                result[i - 1] = '@';
                for (p = i + 1; p < 999; p++)
                    result[p - 1] = m[p + 1];
                result[p - 1] = ' ';
                result[p] = '\0';
                a--;
            }
        }
    }
}

int main() {
    char str[1000], result[1000];
    scanf("%s", str);

    solution(str, result);
    printf("%s", result);
    return 0;
}


dansiliu 注册会员
2023-02-27 14:52

Line 8 when i=998, line 12 starts all i+2=1000, i+3=1003 Isn't that out of bounds? Total size only 1000