# include <iostream>
usingnamespace std;
int make_array_at_p (int **p) {
cout<<"-----------------\n";
*p = newint [10];
cout<<"No segmentation fault\n";
return 10;
}
int main (int argc, char* argv[]) {
int **pointer;
int size = make_array_at_p(pointer);
// do something with array pointed by pointer
return 0;
}
I want to declare a pointer in main(), fill it with data using a function and then use the data further in main().
My actual code needs data in 2D array so I used triple pointer argument for make_array_at_p. But this sample code is sufficient to explain my problem.
Now this code was running fine earlier today on Cygwin in windows 7.
Now it's getting a segmentation fault: 11 on my mac and on online compilers.
I am getting the dashes but the next cout is not being executed.
So I guess, I am making a mistake somewhere.
Can anyone explain to me what am I doing wrong and what is the correct way to deal with this?
you dereferenced the pointer before you allocated anything to it, this should work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# include <iostream>
usingnamespace std;
int make_array_at_p (int **p) {
cout<<"-----------------\n";
p = newint* [10];
cout<<"No segmentation fault\n";
return 10;
}
int main (int argc, char* argv[]) {
int **pointer;
int size = make_array_at_p(pointer);
// do something with array pointed by pointer
return 0;
}
what you're code was trying to do is assign int* [] to a location that should instead hold int []//"/" int and in a better sense that location should have been p[0] but by that time the location din't exist yet.
# include <iostream>
usingnamespace std;
int make_array_at_p (int **p) {
cout<<"-----------------\n";
p = newint* [10];
cout<<"No segmentation fault\n";
for (int i=0; i<10; i++) p[i] = newint[2];
p[0][1] = 39; // check if we can get this data in main()
return 10;
}
int main (int argc, char* argv[]) {
int **pointer;
int size = make_array_at_p(pointer);
// do something with array pointed by pointer
cout<<size<<" rows created\n";
cout<<pointer[0][1]<<"\n";
return 0;
}
Now I can't use the data that I stored in make_array_at_p because p is a local variable of the function.
I do get your point about dereferencing the pointer even before any memory is allocated to it.
But how can I keep accessing memory allocated by a helper function back in main()?
# include <iostream>
usingnamespace std;
int make_array_at_p (int **&p) {
cout<<"-----------------\n";
p = newint* [10];
cout<<"No segmentation fault\n";
for (int i=0; i<10; i++) p[i] = newint[2];
p[0][1] = 39; // check if we can get this data in main()
return 10;
}
int main (int argc, char* argv[]) {
int **pointer;
int size = make_array_at_p(pointer);
// do something with array pointed by pointer
cout<<size<<" rows created\n";
cout<<pointer[0][1]<<"\n";
return 0;
}