Visual Studio - 奇怪的字符输出
Visual Studio - Weird Characters output
我是运行2013年visual studio这个程序,但是打印的是奇怪的字符。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char first[11];
char second[11];
}INFO;
char * str1;
char * str2;
int num;
void bar_function(INFO info)
{
str1 = info.first;
str2 = info.second;
num = 100;
printf("%s %s\n", str1, str2);
}
void print()
{
printf("%s %s\n", str1, str2);
printf("%d\n", num);
}
int main(void)
{
INFO info;
strcpy(info.first, "Hello ");
strcpy(info.second, "World!");
bar_function(info);
print();
system("pause");
return 0;
}
在 bar_function 函数中,我正在为全局变量赋值并打印字符串。它正在打印正确的输出。但是当我在 print 函数中打印相同的字符串时,它在 [ 的输出中打印奇怪的字符=42=]2013。同时 num 变量在 print 函数中打印正确的值.这是相同的输出。
Hello World!
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠─²F ╠╠╠╠╠─²F
100
此外,同一程序在 Codeblocks 中运行良好,并打印正确的值。
我无法理解 visual studio 中的这种奇怪行为。谁能解释一下。
在 bar_function
中,变量 info
是一个 局部变量 ,因此当函数 returns.
这意味着指向数组的指针将变得无效,取消引用它们将导致 undefined behavior。
由于您声称 正在编写 C++ 程序,因此您应该对字符串使用 std::string
,而不是指针或数组。当然也尽量避免使用全局变量。
我是运行2013年visual studio这个程序,但是打印的是奇怪的字符。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char first[11];
char second[11];
}INFO;
char * str1;
char * str2;
int num;
void bar_function(INFO info)
{
str1 = info.first;
str2 = info.second;
num = 100;
printf("%s %s\n", str1, str2);
}
void print()
{
printf("%s %s\n", str1, str2);
printf("%d\n", num);
}
int main(void)
{
INFO info;
strcpy(info.first, "Hello ");
strcpy(info.second, "World!");
bar_function(info);
print();
system("pause");
return 0;
}
在 bar_function 函数中,我正在为全局变量赋值并打印字符串。它正在打印正确的输出。但是当我在 print 函数中打印相同的字符串时,它在 [ 的输出中打印奇怪的字符=42=]2013。同时 num 变量在 print 函数中打印正确的值.这是相同的输出。
Hello World!
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠─²F ╠╠╠╠╠─²F
100
此外,同一程序在 Codeblocks 中运行良好,并打印正确的值。
我无法理解 visual studio 中的这种奇怪行为。谁能解释一下。
在 bar_function
中,变量 info
是一个 局部变量 ,因此当函数 returns.
这意味着指向数组的指针将变得无效,取消引用它们将导致 undefined behavior。
由于您声称 正在编写 C++ 程序,因此您应该对字符串使用 std::string
,而不是指针或数组。当然也尽量避免使用全局变量。