I am running this program in visual studio 2013, but it is printing strange characters.
#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;
}
in bar_function function, I am assigning values to global variables and printing the strings. It is printing correct output. But when I am printing same strings in print function, It is printing weird characters in output in visual studio 2013. Meanwhile num variable is printing correct value in print function. Here is the output for the same.
Hello World!
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠─²F ╠╠╠╠╠─²F
100
Also, same program is working perfectly in Codeblocks and printing correct values.
I am not able to understand this weird behavior in visual studio. Can someone explain this.
In
bar_function
the variableinfo
is a local variable, and as such it will go out of scope and cease to exist when the function returns.That means the pointers to the arrays will become invalid, and dereferencing them will lead to undefined behavior.
Since you claim to be programming C++ you should use
std::string
for strings, instead of pointers or arrays. And of course avoid global variables as much as possible.