Domanda

when i have run this code in dev i have a segmentation fault. in line "*(ap + j) = new int[10];"

int main(){
    int** ap;
    for(int j=0;j<10;j++){
        *(ap + j) = new int[10];
        for(int k=0;k<10;k++){
            *(*(ap+j) +k) = 1;
        }
    }
return 0;
}
È stato utile?

Soluzione

You never allocate any memory for ap. Something like:

int** ap;
ap = new int*[10];

is what you want.

Altri suggerimenti

You are allocating memory for the data but are not allocating memory for the pointer array. It might be enough for you to change the declaration of ap to int* ap[10];.

In *(ap + j) = new int[10]; you dereference memory location which is not allocated yet. First you have to allocate variable ap itself.

Your problem here is *(ap +j) = new ...

Where you are assigning memory for the location "ap+j", the problem is ap + j is not yet a valid memory location because you have not initialized ap. So when you add j to ap you go into uninitialized memory space and therefore get your segmentation fault.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top