I wrote a simple program to test array pointer:
#include <iostream>
using namespace std;
int main(){
int (*array)[10];
int i, j;
for (i = 0; i < 10; i++){
for (j = 0; j < 10; j++)
array[i][j] = 1;
}
for (i = 0; i < 10; i++){
for (j = 0; j < 10; j++)
cout << array[i][j] << " ";
cout << endl;
}
return 0;
}
why the g++ “Segmentation fault”?
by the way, my os is ios x64.
Thanks
Chuan
arrayis a pointer to an array, which you apparently already know. However, you never allocated memory for the actual array, i.e. your pointer is pointing “nowhere”. You are trying to access something that does not exist, which often leads to segmentation fault.For example, you can declare an actual array
and make your pointer point to it
(more precisely, your pointer is now pointing to the first 10-element subarray in
array10x10). After that your code will work fine, meaning that by accessingarray[i][j]you will indirectly accessarray10x10[i][j].Alternatively you can allocate the actual array in dynamic memory, if you so desire
(just don’t forget to do a
delete[] arrayat the end).