在下面的程序中,我通过为它分配NULL来创建*ptr.据我所知,*ptr = NULL; 意思是,*ptr指向什么都没有.如果是这种情况,为什么ptr和&ptr给出不同的结果?
#include<stdio.h>
int main() {
int *ptr=NULL;
printf("%p \n",ptr);
printf("%p \n",&ptr);
}
Run Code Online (Sandbox Code Playgroud)
输出:
0
0x7fff3415dc40
Run Code Online (Sandbox Code Playgroud) 在下面,我试图在使用malloc()分配的内存后释放并对char*进行NULL化.请帮我确定根本原因.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
char *str1="hello world";
char *str2=malloc((strlen(str1)+1) * sizeof(char));
str2=str1;
printf("%s",str2);
free(str2);
str2=NULL;
}
Run Code Online (Sandbox Code Playgroud)
-
错误是:
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud) 我是C++的新手.学习构造函数.请参阅下面提到的两个代码,并提供原因,为什么代码2不起作用.谢谢.
代码1:
#include <iostream>
using namespace std;
class Box
{
int x;
public:
Box::Box(int a=0)
{
x = a;
}
void print();
};
void Box::print()
{
cout << "x=" << x << endl;
}
int main()
{
Box x(100);
x.print();
}
Run Code Online (Sandbox Code Playgroud)
代码2:
#include <iostream>
using namespace std;
class Box
{
int x;
public:
Box(int a=0);
void print();
};
Box::Box(int a=0)
{
x = a;
}
void Box::print()
{
cout << "x=" << x << endl;
}
int main()
{
Box …Run Code Online (Sandbox Code Playgroud)