This is a small snippet of code I was writing to test my knowledge of pointer :
int *grades;
*(grades+0) = 100;
*(grades+1) = 87;
*(grades+2) = 99;
*(grades+3) = 92;
cout<<*(grades+0)<<endl;
cout<<*(grades+1)<<endl;
cout<<*(grades+2)<<endl;
cout<<*(grades+3)<<endl;
I know the flaw in assigning pointers like this. However the above snippet of code correctly printed out the value of each of the grades. The issue is if I use a for loop to automate the display of the content of the pointers.
int *grades;
*(grades+0) = 100;
*(grades+1) = 87;
*(grades+2) = 99;
*(grades+3) = 92;
for(int i=0;i<4;++i)cout<<*(grades+i)<<endl;
Why does addition of a for loop causing segmentation fault. I know the reason of the segmentation fault, but isn't both snippets of code basically the same? I was using https://www.onlinegdb.com/ for writing the code.
pand indexi, the expressionp[i]is exactly equal to*(p + i). I suggest you always use the former syntax (p[i]) because it's generally easier to read and understand. And also less to write.