c++ - I am getting "Segmentation Fault" dereferencing certain indices. How to fix it? -


here code causing error:

  int *marks[4];   cout<<"\nplease enter marks of pf: ";   cin>>*marks[0];   cout<<"\nplease enter marks of la: ";   cin>>*marks[1];   cout<<"\nplease enter marks of cs: ";   cin>>*marks[2];   cout<<"\nplease enter marks of phy: ";   cin>>*marks[3];   cout<<"\nplease enter marks of prob: ";   cin>>*marks[4]; 

i error after entering first 2 values marks[0] & marks[1].

if you're declaring

int *marks[4]; 

that doesn't mean there's appropriate piece of memory allocated particular pointers in array.

you have allocate memory, before write there using statement

cin >> *marks[0]; 

allocate memory follows:

for(size_t = 0; < 4; ++i) {     marks[i] = new int(); } 

before calling cin << operation.
, don't forget deallocate, after shouldn't used longer:

for(size_t = 0; < 4; ++i) {     delete marks[i]; } 

the better solution use std::array<int,[size compiletime determined]> or std::vector<int>:

std::vector<int> marks; 

depending if need fixed size array, or dynamically allocated array can use either

const int fixed_array_size = 30; std::array<int,fixed_array_size> marks; 

size_t array_size = 0: std::cin >> array_size; std::vector<int> marks(array_size); 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -