【发布时间】:2018-07-22 15:52:56
【问题描述】:
我在 Visual Studio 2013 中运行这个程序,但它打印出奇怪的字符。
#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 函数中打印相同的字符串时,它会在 visual studio 2013 的输出中打印奇怪的字符.同时 num 变量在 print 函数中打印正确的值。这是相同的输出。
世界你好!
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠─²F╠╠╠╠╠─²F
100
此外,相同的程序在代码块中完美运行并打印正确的值。
我无法理解 Visual Studio 中的这种奇怪行为。谁能解释一下。
【问题讨论】:
-
将
void bar_function(INFO info)更改为void bar_function(INFO & info)或复制 bar_function 中的 c 字符串。记住 info 是 bar_function() 的局部变量,当它超出 c-strings 的范围时,它不再存在。
标签: c++ visual-studio visual-studio-2013