-5
#include <stdlib.h>
int main(){
    int *array = new int[2];
    array[0] = 1;
    array[1] = 2;
    int ** dp = NULL;
    *dp = array;
    return 0;
}    

when I run it ,Segmentation fault (core dumped). g++ version is

Reading specs from /usr/lib/gcc/x86_64-redhat-linux/3.4.5/specs Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --disable-checking --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-java-awt=gtk --host=x86_64-redhat-linux Thread model: posix gcc version 3.4.5 20051201 (Red Hat 3.4.5-2)

imotai
  • 2,006
  • 1
  • 12
  • 9
  • 3
    Dereferencing a null pointer is undefined behavior. –  Nov 09 '14 at 15:03
  • I hope you're only trying out pointers in order to understand them. In your code example, none of the pointers used are actually required. You should have used local variables instead of dynamically allocated ones. Please read and try to understand: https://stackoverflow.com/questions/22146094/why-should-i-use-a-pointer-rather-than-the-object-itself – Baiz Nov 09 '14 at 15:57

2 Answers2

1

Change the following statements

int ** dp = new int *;

*dp = array;

Or even you could write one statement instead of the two above

int ** dp = new int *( array );

Also do not forget to free the allocated memory

delete dp;
delete []array;

As for your code then you are trying to dereference a null pointer.

Take into account that C header <stdlib.h> in C++ is named like <cstdlib>. And this header is not used in your program. So you may remove it.

The program could look like

#include <iostream>

int main() 
{
    int *array = new int[2] { 1, 2 };
    int ** dp = new int *( array );

    std::cout << ( *dp )[0] << '\t' << ( *dp )[1] << std::endl;

    delete dp;
    delete []array;

    return 0;
}

The output is

1   2
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

This line

*dp = array;

does not do what you intend. 'dp' is a pointer to a pointer and its initial value is zero (NULL). So you are trying to tell the system to place the address of 'array' to memory location 0 which is illegal. To make it work first you need to allocate a number of int *

dp = new int*[5];  // for example...
dp[0] = array;

This will assign the first pointer to your array

DNT
  • 2,356
  • 14
  • 16