Ada*_*yne 0 c++ arrays pointers dynamic-memory-allocation dereference
所以我最近遇到了以下代码:
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];
}
}
Run Code Online (Sandbox Code Playgroud)
当我使用一维指针数组时,需要使用两次解除引用.一旦到达数组的第n个指针(在这种情况下为"s-> marks [i]"),第二次获得指向的实际值,我认为这意味着像这样写:
*(s->marks[i])
Run Code Online (Sandbox Code Playgroud)
这显然不需要,虽然我认为这将返回指针"marks [i]"包含的内存序列号.另一方面,需要取消引用作为单个变量的"数字"指针,如下所示:
*(s->number)
Run Code Online (Sandbox Code Playgroud)
这完全明白了.
有人可以向我解释(或指向一篇好文章)为什么在使用动态分配的指针数组时不需要使用解引用运算符,在本例中为"标记".我也对使用"name"char数组指针感到困惑,它使用的方式与普通的char变量相似.
在此先感谢所有的帮助.
编辑总结:
我刚才意识到这一点
/*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
Run Code Online (Sandbox Code Playgroud)
我以为我正在处理类似于第一对陈述的事情.实际上,我不得不处理第二对.
s->marks是指向数组的第一个元素的指针double.
s->marks + i是指向ith元素的指针.
*(s->marks + i)取消引用double元素本身.
s->marks[i]是一种方便的写作方式*(s->marks + i).它包括解除引用操作,因此不需要另一个.