c++打印指针本身的值
时间: 2023-08-05 10:04:10 浏览: 47
要打印指针本身的值,可以使用`printf`函数配合格式化字符串`%p`,如下所示:
```c++
#include <cstdio>
int main() {
int* ptr = nullptr;
printf("Pointer value: %p\n", (void*)ptr);
return 0;
}
```
这里将指针强制转换成`void*`类型,是为了让编译器正确地解释它。如果不这样做,编译器可能会出现警告。
相关问题
C++链表类
好的,下面是一个简单的 C++ 链表类的示例代码:
```c++
#include <iostream>
using namespace std;
class ListNode {
public:
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class LinkedList {
public:
LinkedList() {
head = NULL;
}
~LinkedList() {
ListNode* curr = head;
while (curr != NULL) {
ListNode* temp = curr->next;
delete curr;
curr = temp;
}
head = NULL;
}
void add(int val) {
ListNode* node = new ListNode(val);
if (head == NULL) {
head = node;
} else {
ListNode* curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = node;
}
}
void print() {
ListNode* curr = head;
while (curr != NULL) {
cout << curr->val << " ";
curr = curr->next;
}
cout << endl;
}
private:
ListNode* head;
};
int main() {
LinkedList list;
list.add(1);
list.add(2);
list.add(3);
list.print();
return 0;
}
```
在这个示例代码中,我们定义了一个 `ListNode` 类,表示链表中的一个节点,包含一个 `int` 类型的值和一个指向下一个节点的指针。然后我们定义了一个 `LinkedList` 类,表示链表本身,包含一个指向链表头部的指针。我们可以通过 `add` 方法向链表中添加元素,通过 `print` 方法打印链表中的所有元素。在 `LinkedList` 类的析构函数中,我们确保释放链表中所有节点的内存。
c++ 函数传入数组
当我们在函数中传递数组时,可以使用指针来实现。在 C 语言中,数组名本身即是指向数组第一个元素的指针。
下面是一个示例代码,展示了如何在函数中传递数组:
```c
#include <stdio.h>
// 函数接受一个整型数组和数组的长度作为参数
void printArray(int arr[], int length) {
for (int i = 0; i < length; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int nums[] = {1, 2, 3, 4, 5};
int length = sizeof(nums) / sizeof(nums[0]);
printArray(nums, length);
return 0;
}
```
在上面的示例中,我们定义了一个 `printArray` 函数,该函数接受一个整型数组 `arr[]` 和数组的长度 `length` 作为参数。在 `main` 函数中,我们创建了一个整型数组 `nums`,并通过 `sizeof` 运算符计算出数组的长度,并将其传递给 `printArray` 函数。
在 `printArray` 函数中,我们使用循环遍历数组并打印每个元素。
输出结果:
```
1 2 3 4 5
```
通过以上示例,我们可以看到在函数中传递数组只需传递数组名以及数组的长度即可。注意,我们并没有在函数定义中指定数组的长度,而是在调用函数时传递进去的。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)