So I recently came across the following piece of code:
struct Student
{
int *number;
char *name;
double *marks;
};
int main(){
int n;
Student *s;
s = new Student;
cout << "Enter the number of subjects the student learns: ";
cin >> n;
s->number= new int;
s->name=new char[20];
s->marks=new double[n];
cout << "Enter the name of the student: ";
cin >> s->name;
cout << "Enter the number in class of " << s->name << ": ";
cin >> *(s->number);
for (int i = 0 ; i < n ; i++){
cout << "Enter mark No" << i+1 << " of the student: ";
cin >> s->marks[i];
}
}
When I worked with one dimensional arrays of pointers there was the need to use dereference twice. Once to reach the n-th pointer of the array ("s->marks[i]" in this case) and a second time to get the actual value that is pointed which I thought meant to write it like this:
*(s->marks[i])
This is apparently not needed, although I thought this would return the memory serial number contained by the pointer "marks[i]". On the other hand, there is the need to dereference the "number" pointer that is a single variable like that:
*(s->number)
This I perfectly understand.
Can someone please explain to me (or point me to a good article) why there is no need to use the dereference operator when working with dynamically allocated pointer arrays like, in this case, "marks". I am also confused with the use of the "name" char array pointer which is used rather like a normal char variable.
Thanks in advance for all the help.
Edit to sum up:
I just now realised that
/*the following two statements declare an array of pointers hence allow for the
use of double dereference*/
int* marks[n]; //static memory allocation
int** marks=new int*[n]; //dynamic memory allocation
/*the following two statements declare an array of variables hence allow for the
use of only one dereference (just a simple 1 dimensional array)*/
int marks[n]; //static memory allocation
int* marks=new int[n]; //dynamic memory allocation
I thought that I was dealing with something similar to the first pair of statements. In reality, I had to deal with the second pair.
s->marks
is a pointer to the first element of an array of double
.
s->marks + i
is a pointer to the i
th element.
*(s->marks + i)
dereferences that to give the double
element itself.
s->marks[i]
is a convenient way to write *(s->marks + i)
. It includes the dereference operation, so there's no need for another one.