在函数中使用字符串参数时,为什么我的变量在退出程序后损坏(运行时检查失败)

时间:2017-04-18 06:00:08

标签: c pointers visual-studio-2015 parameters runtime-error

我正在尝试使用从func1传递到func2的字符串参数。

所有消息都以正确的顺序显示,但在我退出程序后,Visual Studio 2015向我显示了警告:

运行时检查失败#2 - 围绕变量' y'已损坏

以下是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning (disable:4996)

//Functions declaration
int func1(char x[], char y[]);
int func2(char x[], char y[]);

void main() {
    char x[25], y[25];

    strcpy(x, "x-coordinate");
    strcpy(y, "y-coordinate");

    printf("Passing 'x' and 'y' strings to func1()");
    func1(x, y);

    system("pause");

}

int func1(char x[], char y[]){
    strcpy(x, "x-coordinate received by func1()");
    strcpy(y, "y-coordinate received by func1()");

    printf("\n%s", x);
    printf("\n%s", y);

    printf("\n\nPassing 'x' and 'y' strings to func2()");
    func2(x, y);
}

int func2(char x[], char y[]) {
    strcpy(x, "x-coordinate received by func2()");
    strcpy(y, "y-coordinate received by func2()");

    printf("\n%s", x);
    printf("\n%s", y);
    printf("\n");
}

我犯了什么错误?

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:3)

xy是大小为25的数组,您可以在此处将更大尺寸的字符串复制到其中:

strcpy(x, "x-coordinate received by func1()");
strcpy(y, "y-coordinate received by func1()");

在这里:

strcpy(x, "x-coordinate received by func2()");
strcpy(y, "y-coordinate received by func2()");

答案 1 :(得分:2)

这是因为您仅将strcpy后的值用于printf。您不需要将要打印的字符串分配给变量(x或y)。

你可以这样做:

printf("\n x-coordinate received by func1()");

如果你这样做,你可以节省一些strcpy(他们花费时间O(n),其中n是字符串的长度)