请注意,本文编写于 253 天前,最后修改于 253 天前,其中某些信息可能已经过时。
据说 C/C++ 语言的灵魂就是指针,不论是什么类型,都可以声明到指针型变量。当然,还有什么地址引用(&符号),内存申请,结点式结构体中的指针(链表)等等,今天就来一并消灭这些障碍。
根据下面的例子可知, 和 & 运算符可逆,& 取地址,结果为指针; 取指针,结果为地址;
#include <iostream>
using namespace std;
int main() {
int p1 = 10;
int *p2 = &p1;
cout << "p1: " << p1 << endl; // 结果为:10
cout << "p2: " << p2 << endl; // 结果为:0x61ff08
cout << "*p2" << *p2 << endl; // 结果为:10
cout << "&*p2 " << &*p2 << endl; // 结果为:0x61ff08
};
在做链表类含有结点的题目的时候,一般都需要先声明一个结构体。如果结构体后紧跟指针变量,需要进行内存的分配:C++ 中使用 new 关键字,C 语言中使用 malloc 函数(还需引入 stdlib 头文件)。
// C++ file
#include <iostream>
using namespace std;
struct Student {
int a = 10;
} *stu; // 只是声明,没有分配内存。
int main() {
stu = new Student; // 如果没有此式,会发生不可预知的错误。因为此时 stu 并没有给它分配内存。
cout << stu -> a << endl;
};
// c file
#include <stdio.h>
#include <stdlib.h>
struct Student {
int a;
}*stu;
int main() {
stu = (struct Student*) malloc(sizeof(stu)); // (*)
stu = (struct Student*) malloc(sizeof(struct Student)); // (**)
stu -> a = 10;
printf("%d", stu -> a);
return 0;
};
// 显示类型变换括号内要写成 struct Student* 否则会产生错误
// (*) 和 (**) 都是正确的,malloc 前的显示类型变换中一定要是指针类型,因为 malloc 返回的就是指针。
下面的代码实现了声明一个结点结构体,并将两个结点连接在一起。
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
};
int main() {
Node* head = new Node;
Node* body = new Node;
head -> next = body;
body -> data = 10;
cout << head -> next -> data << endl;
return 0;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node* next;
} Node;
int main() {
Node* head = (Node*)malloc(sizeof(Node));
Node* body = (Node*)malloc(sizeof(Node));
head -> next = body;
body -> data = 10;
printf("%d", head->next->data);
return 0;
};
全部评论 (暂无评论)
info 还没有任何评论,你来说两句呐!