指针和引用(C++)
Pointers and references (C++)
这个while
没有停止,似乎陷入了一个无休止的循环:
struct list_elem<int[5]> *p, *pCopy; // list_elem is the node struct
p = l.pfirst; // l is the LL object
pCopy = p->next;
while(p != NULL) {
//bunch of code
p = pCopy;
}
将结束问题
简单地说,pCopy
是一个常数,因为它在循环之外。感谢您对的帮助
这就是迭代的方式:
while(p != NULL) {
p = p->next;
}
.
运算符用于局部结构,而->
取消引用指针:
#include <stdio.h>
#include <string.h>
struct my_struct {
int id;
struct my_struct *next;
}
int main()
{
struct my_struct *a, *b, *c;
a = malloc(sizeof(struct my_struct));
b = malloc(sizeof(struct my_struct));
c = malloc(sizeof(struct my_struct));
a->next = b;
a->id = 1;
b->next = c;
b->id = 2;
c->next = NULL;
c->id = 3;
struct my_struct *it = a;
printf("Using pointers:nn");
while(it != NULL) {
printf("Element %dn", it->id);
it = it->next;
}
struct my_struct d, e, f;
d.next = &e;
d.id = 1;
e.next = &f;
e.id = 2;
f.next = NULL;
f.id = 3;
it = &d;
printf("Using locals:nn");
while(it != NULL) {
printf("Element %dn", it->id);
it = (it->next);
}
free(a);
free(b);
free(c);
return 0;
}
您应该在谷歌上搜索一个关于C的教程,并在第一行尝试理解指针算术。
while ((p = p->next) != NULL);
您所拥有的并不是真正浏览列表,只是一遍又一遍地将其自身设置为相同的
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?