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

C 为什么在函数中使用字符串参数时退出程序后我的变量已损坏(运行时检查失败),c,pointers,visual-studio-2015,parameters,runtime-error,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 fun

我试图使用字符串参数从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");
}
#包括
#包括
#包括
#杂注警告(禁用:4996)
//功能声明
int func1(字符x[],字符y[]);
int func2(字符x[],字符y[]);
void main(){
字符x[25],y[25];
strcpy(x,“x坐标”);
strcpy(y,y坐标);
printf(“将'x'和'y'字符串传递给func1()”;
func1(x,y);
系统(“暂停”);
}
int func1(字符x[],字符y[]{

strcpy(x,“func1()接收到的x坐标”); strcpy(y,“func1()接收的y坐标”); printf(“\n%s”,x); printf(“\n%s”,y); printf(“\n\n将'x'和'y'字符串处理为func2()”; func2(x,y); } int func2(字符x[],字符y[]{ strcpy(x,“func2()接收到的x坐标”); strcpy(y,“func2()接收的y坐标”); printf(“\n%s”,x); printf(“\n%s”,y); printf(“\n”); }
我犯了什么错误


任何帮助都将不胜感激。

x
y
是大小为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()");

x
y
是大小为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()");

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

你可以做:

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

如果您这样做,您可以为自己保存一些
strcpy
(它们需要时间O(n),其中n是字符串的长度)

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

你可以做:

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

如果您这样做,您可以为自己保存一些strcpy(它们需要时间O(n),其中n是字符串的长度)

您写入的数组超出了现有数组的边界。这会导致未定义的行为,从而导致程序格式错误和无效。故事结束。“func1()接收到的x坐标”超过25个字符您写入的数组超出了范围。这会导致未定义的行为,从而导致程序格式错误和无效。故事结束。“func1()接收到的x坐标”超过25个字符a,我不知道为什么我可以编写这样无效的代码。谢谢你纠正我的错误。:)是啊,我不知道为什么我能写这么低效的代码。谢谢你纠正我的错误。:)