I am trying to use string parameter passing from func1 to func2.
我正在尝试使用从func1传递到func2的字符串参数。
All the messages displayed in correct order, but after I exited the program, Visual Studio 2015 showed me a warning:
所有消息都以正确的顺序显示,但在我退出程序后,Visual Studio 2015向我显示了一个警告:
Run-Time Check Failure # 2 - Stack around the variable 'y' was corrupted
运行时检查失败#2 - 变量'y'周围的堆栈已损坏
Below is my codes:
以下是我的代码:
#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");
}
What mistake I made?
我犯了什么错误?
Any help would be appreciated.
任何帮助,将不胜感激。
2 个解决方案
#1
3
x
and y
are arrays of size 25 and you copy strings of larger size into them in here:
x和y是大小为25的数组,你可以在这里复制更大尺寸的字符串:
strcpy(x, "x-coordinate received by func1()");
strcpy(y, "y-coordinate received by func1()");
and here:
strcpy(x, "x-coordinate received by func2()");
strcpy(y, "y-coordinate received by func2()");
#2
2
It's because you use the values after strcpy
only to printf
. You don't need to assign the strings you want to print to a variable (x nor y).
这是因为你只将strcpy之后的值用于printf。您不需要将要打印的字符串分配给变量(x或y)。
You can do:
你可以做:
printf("\n x-coordinate received by func1()");
If you do it like this, you save yourself some strcpy
(they take time O(n) where n is the length of the string)
如果你这样做,你可以节省一些strcpy(它们需要时间O(n),其中n是字符串的长度)
#1
3
x
and y
are arrays of size 25 and you copy strings of larger size into them in here:
x和y是大小为25的数组,你可以在这里复制更大尺寸的字符串:
strcpy(x, "x-coordinate received by func1()");
strcpy(y, "y-coordinate received by func1()");
and here:
strcpy(x, "x-coordinate received by func2()");
strcpy(y, "y-coordinate received by func2()");
#2
2
It's because you use the values after strcpy
only to printf
. You don't need to assign the strings you want to print to a variable (x nor y).
这是因为你只将strcpy之后的值用于printf。您不需要将要打印的字符串分配给变量(x或y)。
You can do:
你可以做:
printf("\n x-coordinate received by func1()");
If you do it like this, you save yourself some strcpy
(they take time O(n) where n is the length of the string)
如果你这样做,你可以节省一些strcpy(它们需要时间O(n),其中n是字符串的长度)