小编Bah*_*ali的帖子

NULL指针的地址

在下面的程序中,我通过为它分配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)

c null pointers

2
推荐指数
2
解决办法
4008
查看次数

在C中,无法释放并为char指针分配NULL

在下面,我试图在使用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 malloc segmentation-fault

1
推荐指数
1
解决办法
60
查看次数

下面给出的代码中的C++构造函数定义差异

我是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)

c++ class-constructors

-1
推荐指数
1
解决办法
77
查看次数