C++ 为什么动态分配的指针数组不需要解引用就可以到达它们的实际成员
因此,我最近遇到了以下代码:C++ 为什么动态分配的指针数组不需要解引用就可以到达它们的实际成员,c++,arrays,pointers,dynamic-memory-allocation,dereference,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->n
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];
}
}
这显然是不需要的,尽管我认为这将返回指针“marks[I]”所包含的内存序列号。另一方面,需要取消对“数字”指针的引用,该指针是单个变量,如下所示:
*(s->number)
这我完全理解
有人能给我解释一下(或者给我指出一篇好文章)为什么在处理动态分配的指针数组时不需要使用解引用操作符,比如在本例中的“marks”。我还对“name”字符数组指针的使用感到困惑,它的使用方式与普通字符变量非常相似
提前感谢您的帮助。编辑汇总:
我刚刚意识到
/*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
我以为我在处理与第一对语句类似的事情。实际上,我必须处理第二对。
s->marks
是指向双精度数组的第一个元素的指针
s->marks+i
是指向i
th元素的指针
*(s->marks+i)
取消对其的引用,以给出双元素本身
s->marks[i]
是编写*(s->marks+i)
的便捷方法。它包括解引用操作,因此不需要另一个
int x = 10;
int *p = &x;
然后表达
*p = 20;
p[0] = 20;
cin >> *(s->number);
相当于表达式
*p = 20;
p[0] = 20;
cin >> *(s->number);
相对于您可以编写的代码
cin >> s->number[0];
cin >> *( s->marks + i );
而不是
cin >> *(s->number);
cin >> s->marks[i];
就像你写的一样
cin >> s->number[0];
cin >> *( s->marks + i );
而不是
cin >> *(s->number);
cin >> s->marks[i];
根据C++标准
表达式E1[E2]根据定义与*((E1)+(E2))相同
再次返回代码表达式
*p = 20;
p[0] = 20;
cin >> *(s->number);
可以写成
cin >> *(s->number + 0);
就是
cin >> s->number[0];
如果Student
对象不是不必要的动态分配,可能更容易理解。这是一段糟糕的代码,不要把它作为一个例子来说明事情是如何完成的。是的,但是标记是一个指针数组,所以我认为s->marks[I]将返回一个指针,而不是一个双精度指针variable@AdamPayne:否,它是指向double
数组的(第一个元素)指针。指向指针数组的指针看起来像double**
@AdamPaynemarks
不是数组,它只是指向double
的单个指针。它指向一个动态分配的double
数组。