1. 字符串:
#include <iostream>
using namespace std;
int main()
{
char str[100] = "abc";
int a = int(str);
int b = int(&str);
if(a == b)
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
return 0;
}
结果是yes, 可见, str和&str的值是相同的。 仅仅是值相同。
看看下面的程序:
#include <iostream>
using namespace std;
int main()
{
char str[100] = "abc";
memset(&str, 0, sizeof(str));
return 0;
}
上面程序有错误, 但是, 运气够好的, &str刚好和str相等。应该改为:
#include <iostream>
using namespace std;
int main()
{
char str[100] = "abc";
memset(str, 0, sizeof(str));
return 0;
}
2. 整数
#include <iostream>
using namespace std;
int main()
{
int a[100];
memset(a, 0, 100);
int i = 0;
for(i = 0; i < 100; i++)
{
cout << a[i] << endl; // 很多都非零
}
return 0;
}
应该改为:
#include <iostream>
using namespace std;
int main()
{
int a[100];
memset(a, 0, 100 * sizeof(int));
int i = 0;
for(i = 0; i < 100; i++)
{
cout << a[i] << endl; //全部为0
}
return 0;
}
或者改为更好的:
#include <iostream>
using namespace std;
int main()
{
int a[100];
memset(a, 0, sizeof(a));
int i = 0;
for(i = 0; i < 100; i++)
{
cout << a[i] << endl;
}
return 0;
}
当然, 如果是初始化, 用int a[100] = {0}; 也未尝不可。
3. c++ string
骇人听闻的段错误,下面程序, 在vc++6.0中居然不报错:
#include <iostream>
#include <string>
using namespace std;
typedef struct _test
{
int score;
string name;
}Student;
int main()
{
Student a;
memset(&a, 0, sizeof(a));
a.name = "lily";
cout << a.name.c_str() << endl;
return 0;
}
如果在linux, 运行程序, 就会出现段错误, 原因:string不能memset, 为什么? 查查memset的用法吧。 最近在实际中遇到了这个问题, 略作记录, 请大家注意。
最后再补充一个, 内存重叠时, 不要用memcpy, 要用memmove.