如何解决如何适当地初始化指针以避免c ++中的分段错误?
我已经开始学习c ++(来自Java背景),几乎没有达到指针并陷入困境。当我调试该程序时,它说,程序在行上收到分段错误(SIGSEGV信号)
* prevIoUs = head;
在以下代码中。
[19:05]/tmp/tergent->master $ cargo build --target=armv7-linux-androideabi --verbose
Fresh autocfg v1.0.0
Fresh cfg-if v0.1.10
Fresh unicode-xid v0.2.1
Fresh ppv-lite86 v0.2.8
Fresh itoa v0.4.6
Fresh base64 v0.12.3
Fresh once_cell v1.4.0
Fresh hex v0.4.2
Fresh libc v0.2.74
Fresh proc-macro2 v1.0.19
Fresh serde v1.0.114
Fresh ryu v1.0.5
Fresh bitflags v1.2.1
Fresh num-traits v0.2.12
Fresh getrandom v0.1.14
Fresh time v0.1.43
Fresh quote v1.0.7
Fresh num-integer v0.1.43
Fresh rand_core v0.5.1
Fresh nix v0.18.0
Fresh serde_json v1.0.57
Fresh rand_chacha v0.2.2
Fresh syn v1.0.38
Fresh num-bigint v0.2.6
Fresh chrono v0.4.13
Fresh rand v0.7.3
Fresh num-derive v0.3.1
Fresh simple_asn1 v0.4.1
Fresh uuid v0.8.1
Compiling tergent v1.0.0 (/tmp/tergent)
Running `rustc --crate-name tergent --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi --crate-type cdylib --emit=dep-info,link -Cembed-bitcode=no -C debuginfo=2 -C Metadata=b6a2965ef93bb5e8 --out-dir /tmp/tergent/target/armv7-linux-androideabi/debug/deps --target armv7-linux-androideabi -C 'linker=/home/rebel/$HOME/Android/NDK/arm/bin/arm-linux-androideabi-clang' -C incremental=/tmp/tergent/target/armv7-linux-androideabi/debug/incremental -L dependency=/tmp/tergent/target/armv7-linux-androideabi/debug/deps -L dependency=/tmp/tergent/target/debug/deps --extern base64=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libbase64-04c3ff0d903d612e.rlib --extern bitflags=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libbitflags-0839c713eceb861a.rlib --extern hex=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libhex-d4ae58abeaa8109d.rlib --extern nix=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libnix-a9ab1027aef873d6.rlib --extern num_derive=/tmp/tergent/target/debug/deps/libnum_derive-29bdb6f1125bd4f2.so --extern num_traits=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libnum_traits-84af4dabd83ecda9.rlib --extern once_cell=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libonce_cell-93c75b6cffc1ed95.rlib --extern serde_json=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libserde_json-33982e169e2395ce.rlib --extern simple_asn1=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libsimple_asn1-9807816f7d31f61c.rlib --extern uuid=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libuuid-c723d9c5bf67b153.rlib`
error[E0308]: mismatched types
--> src/lib.rs:114:38
|
114 | token_info.total_public_memory = unavailable_information;
| ^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,found `u64`
|
help: you can convert `token_info.total_public_memory` from `u32` to `u64`,matching the type of `unavailable_information`
|
114 | u64::from(token_info.total_public_memory) = unavailable_information;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0308]: mismatched types
--> src/lib.rs:115:37
|
115 | token_info.free_public_memory = unavailable_information;
| ^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,found `u64`
|
help: you can convert `token_info.free_public_memory` from `u32` to `u64`,matching the type of `unavailable_information`
|
115 | u64::from(token_info.free_public_memory) = unavailable_information;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0308]: mismatched types
--> src/lib.rs:116:39
|
116 | token_info.total_private_memory = unavailable_information;
| ^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,found `u64`
|
help: you can convert `token_info.total_private_memory` from `u32` to `u64`,matching the type of `unavailable_information`
|
116 | u64::from(token_info.total_private_memory) = unavailable_information;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0308]: mismatched types
--> src/lib.rs:117:38
|
117 | token_info.free_private_memory = unavailable_information;
| ^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,found `u64`
|
help: you can convert `token_info.free_private_memory` from `u32` to `u64`,matching the type of `unavailable_information`
|
117 | u64::from(token_info.free_private_memory) = unavailable_information;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0308]: mismatched types
--> src/lib.rs:196:33
|
196 | unsafe { *session = index }
| ^^^^^ expected `u32`,found `u64`
|
help: you can convert `*session` from `u32` to `u64`,matching the type of `index`
|
196 | unsafe { u64::from(*session) = index }
| ^^^^^^^^^^^^^^^^^^^
error[E0308]: mismatched types
--> src/lib.rs:208:25
|
208 | match state::remove(session) {
| ^^^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `session.into()`
error[E0308]: mismatched types
--> src/lib.rs:304:28
|
304 | let state = state::get(session);
| ^^^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `session.into()`
error[E0277]: the trait bound `u64: std::convert::From<pkcs11::key_type::KeyType>` is not satisfied
--> src/lib.rs:342:18
|
342 | .try_into()
| ^^^^^^^^ the trait `std::convert::From<pkcs11::key_type::KeyType>` is not implemented for `u64`
|
= help: the following implementations were found:
<u64 as std::convert::From<bool>>
<u64 as std::convert::From<std::num::NonZeroU64>>
<u64 as std::convert::From<u16>>
<u64 as std::convert::From<u32>>
<u64 as std::convert::From<u8>>
= note: required because of the requirements on the impl of `std::convert::Into<u64>` for `pkcs11::key_type::KeyType`
= note: required because of the requirements on the impl of `std::convert::TryFrom<pkcs11::key_type::KeyType>` for `u64`
= note: required because of the requirements on the impl of `std::convert::TryInto<u64>` for `pkcs11::key_type::KeyType`
error[E0277]: the trait bound `pkcs11::object_class::ObjectClass: std::convert::From<u64>` is not satisfied
--> src/lib.rs:439:89
|
439 | if let Ok(ObjectClass::PublicKey) | Ok(ObjectClass::PrivateKey) = class.try_into() {
| ^^^^^^^^ the trait `std::convert::From<u64>` is not implemented for `pkcs11::object_class::ObjectClass`
|
= note: required because of the requirements on the impl of `std::convert::Into<pkcs11::object_class::ObjectClass>` for `u64`
= note: required because of the requirements on the impl of `std::convert::TryFrom<u64>` for `pkcs11::object_class::ObjectClass`
= note: required because of the requirements on the impl of `std::convert::TryInto<pkcs11::object_class::ObjectClass>` for `u64`
error[E0308]: mismatched types
--> src/lib.rs:463:28
|
463 | let state = state::get(session);
| ^^^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `session.into()`
error[E0308]: mismatched types
--> src/lib.rs:487:28
|
487 | let state = state::get(session);
| ^^^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `session.into()`
error[E0308]: mismatched types
--> src/lib.rs:643:28
|
643 | let state = state::get(session);
| ^^^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `session.into()`
error[E0308]: mismatched types
--> src/lib.rs:697:32
|
697 | let state = state::get(session);
| ^^^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `session.into()`
error[E0308]: mismatched types
--> src/pkcs11/mod.rs:64:30
|
64 | self.value_len = len;
| ^^^ expected `u32`,found `u64`
|
help: you can convert `self.value_len` from `u32` to `u64`,matching the type of `len`
|
64 | u64::from(self.value_len) = len;
| ^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0308]: mismatched types
--> src/pkcs11/mod.rs:68:29
|
68 | if self.value_len < len {
| ^^^ expected `u32`,matching the type of `len`
|
68 | if u64::from(self.value_len) < len {
| ^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0308]: mismatched types
--> src/pkcs11/mod.rs:75:26
|
75 | self.value_len = len;
| ^^^ expected `u32`,matching the type of `len`
|
75 | u64::from(self.value_len) = len;
| ^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0308]: mismatched types
--> src/pkcs11/notification.rs:16:32
|
16 | Notification::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/notification.rs:23:9
|
22 | fn try_from(value: Notification) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
23 | Notification::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,found `u64`
|
= note: expected enum `std::result::Result<u32,_>`
found enum `std::result::Result<u64,_>`
error[E0308]: mismatched types
--> src/pkcs11/user_type.rs:17:28
|
17 | UserType::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/user_type.rs:24:9
|
23 | fn try_from(value: UserType) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
24 | UserType::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/session_state.rs:19:32
|
19 | SessionState::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/session_state.rs:26:9
|
25 | fn try_from(value: SessionState) -> Result<Self,()>` because of return type
26 | SessionState::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/object_class.rs:24:31
|
24 | ObjectClass::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/object_class.rs:31:9
|
30 | fn try_from(value: ObjectClass) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
31 | ObjectClass::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/hardware_feature_type.rs:18:39
|
18 | HardwareFeatureType::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/hardware_feature_type.rs:25:9
|
24 | fn try_from(value: HardwareFeatureType) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
25 | HardwareFeatureType::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/key_type.rs:56:27
|
56 | KeyType::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/key_type.rs:63:9
|
62 | fn try_from(value: KeyType) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
63 | KeyType::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/certificate_category.rs:18:39
|
18 | CertificateCategory::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/certificate_category.rs:25:9
|
24 | fn try_from(value: CertificateCategory) -> Result<Self,()>` because of return type
25 | CertificateCategory::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/security_domain.rs:18:34
|
18 | SecurityDomain::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/security_domain.rs:25:9
|
24 | fn try_from(value: SecurityDomain) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
25 | SecurityDomain::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/certificate_type.rs:18:35
|
18 | CertificateType::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/certificate_type.rs:25:9
|
24 | fn try_from(value: CertificateType) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
25 | CertificateType::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/attribute_type.rs:120:33
|
120 | AttributeType::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/attribute_type.rs:127:9
|
126 | fn try_from(value: AttributeType) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
127 | AttributeType::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,found `u64`
|
= note: expected enum `std::result::Result<u32,_>`
found enum `std::result::Result<u64,_>`
error[E0308]: mismatched types
--> src/pkcs11/otp.rs:34:26
|
34 | Format::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/otp.rs:41:9
|
40 | fn try_from(value: Format) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
41 | Format::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/otp.rs:48:25
|
48 | Param::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/otp.rs:55:9
|
54 | fn try_from(value: Param) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
55 | Param::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/mechanism_type.rs:338:33
|
338 | MechanismType::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/mechanism_type.rs:345:9
|
344 | fn try_from(value: MechanismType) -> Result<Self,()>` because of return type
345 | MechanismType::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/return_value.rs:109:31
|
109 | ReturnValue::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/return_value.rs:116:9
|
115 | fn try_from(value: ReturnValue) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
116 | ReturnValue::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/mask_generation_function.rs:19:42
|
19 | MaskGenerationFunction::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/mask_generation_function.rs:26:9
|
25 | fn try_from(value: MaskGenerationFunction) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
26 | MaskGenerationFunction::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/key_derivation_function.rs:23:41
|
23 | KeyDerivationFunction::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/key_derivation_function.rs:30:9
|
29 | fn try_from(value: KeyDerivationFunction) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
30 | KeyDerivationFunction::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error[E0308]: mismatched types
--> src/pkcs11/pseudo_random_function.rs:22:40
|
22 | PseudoRandomFunction::from_u64(value).ok_or(())
| ^^^^^
| |
| expected `u64`,found `u32`
| help: you can convert an `u32` to `u64`: `value.into()`
error[E0308]: mismatched types
--> src/pkcs11/pseudo_random_function.rs:29:9
|
28 | fn try_from(value: PseudoRandomFunction) -> Result<Self,Self::Error> {
| ------------------------- expected `std::result::Result<u32,()>` because of return type
29 | PseudoRandomFunction::to_u64(&value).ok_or(())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`,_>`
error: aborting due to 50 prevIoUs errors
Some errors have detailed explanations: E0277,E0308.
For more information about an error,try `rustc --explain E0277`.
error: Could not compile `tergent`.
Caused by:
process didn't exit successfully: `rustc --crate-name tergent --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi --crate-type cdylib --emit=dep-info,link -Cembed-bitcode=no -C debuginfo=2 -C Metadata=b6a2965ef93bb5e8 --out-dir /tmp/tergent/target/armv7-linux-androideabi/debug/deps --target armv7-linux-androideabi -C 'linker=/home/rebel/$HOME/Android/NDK/arm/bin/arm-linux-androideabi-clang' -C incremental=/tmp/tergent/target/armv7-linux-androideabi/debug/incremental -L dependency=/tmp/tergent/target/armv7-linux-androideabi/debug/deps -L dependency=/tmp/tergent/target/debug/deps --extern base64=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libbase64-04c3ff0d903d612e.rlib --extern bitflags=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libbitflags-0839c713eceb861a.rlib --extern hex=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libhex-d4ae58abeaa8109d.rlib --extern nix=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libnix-a9ab1027aef873d6.rlib --extern num_derive=/tmp/tergent/target/debug/deps/libnum_derive-29bdb6f1125bd4f2.so --extern num_traits=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libnum_traits-84af4dabd83ecda9.rlib --extern once_cell=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libonce_cell-93c75b6cffc1ed95.rlib --extern serde_json=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libserde_json-33982e169e2395ce.rlib --extern simple_asn1=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libsimple_asn1-9807816f7d31f61c.rlib --extern uuid=/tmp/tergent/target/armv7-linux-androideabi/debug/deps/libuuid-c723d9c5bf67b153.rlib` (exit code: 1)
为什么指针初始化不正确?
解决方法
第一个问题:
Node *previous;
*previous=head;
第一行声明前一个将保存节点的地址。它没有被初始化,因此无论堆栈上的值是多少,都将作为其持有的位模式被拾取。
不幸的是,第二行然后取消引用指针(指向垃圾),并尝试将head复制到随机内存中(因此导致崩溃)。
在这种情况下,您可能希望上一个指向头,即获取头的地址并分配地址:
Node* previous = &head; // initialize at the point of declaration
但是,您还必须非常警惕指向在堆栈上声明的变量的指针,因为当函数返回或范围退出时,地址将很快变得无效。 (通常,带有指针的数据结构使用的是在堆上分配的值,因此对象的寿命超过了声明它们的函数。)
这给我们带来了第二个问题:
while(!done)
{
cout << i << ": Iteration";
Node temp;
已经有问题了。 temp
在堆栈的循环内声明。每次循环迭代时,变量将被自动销毁。因此,它不能破坏您的链表,而不会破坏它。
您希望使用new
创建列表节点,并且在更新前一个的下一个指针时,想要为其分配地址,而不是通过它复制对象。
类似这样的东西:
while(!done)
{
cout << i << ": Iteration";
Node * temp = new Node();
temp->data = i;
temp->link = nullptr; // better than NULL
if(i > 2)
{
break;
}
previous->link = temp;
++i;
previous = temp;
}
head
对象可能也应该是堆分配的。当然,现在您必须通过在所有节点上调用delete来清理内存。
代码中有一些错误,但主要错误是:-
- 您没有为运行时添加的新节点分配内存
- 您正在创建结构实例,但是需要创建一个指向结构的指针(实例将在运行时创建(使用
new
运算符)
我已经在代码中添加了注释,解释了我所做的更改到底是什么。
这是解决方法:-
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *link;
};
int main()
{
cout << "Starting main program \n";
// Allocating memory for the new instance of Node and making "head" pointing to it
Node *head = new Node;
head->data = 0;
head->link = NULL;
cout << "After declaring head and initializing values \n";
//Declaring a pointer variable which points to an entity of type struct.
Node *previous;
// As head and previous both are pointers thus can be assigned as it is
previous = head;
cout << "After declaring previous pointer \n";
bool done = false;
int i = 1;
cout << "First while loop\n";
while(!done)
{
cout << i << ": Iteration";
// Allocating memory for the new instance of Node and making temp pointing to it
Node *temp = new Node;
// As temp is a pointer thus using member access ("- >") operator to access the members
temp->data=i;
temp->link=NULL;
if(i > 2)
{
done = true;
continue;
}
previous->link = temp;
++i;
previous = temp;
}
done = false;
cout << "Declaring temp pointer before printing \n";
Node *temp;
temp = head;
cout << "Second while loop\n";
while (!done)
{
cout << i << ": Iteration";
if(temp == NULL)
{
done = true;
continue;
}
cout << temp->data << "->";
temp = temp->link;
}
cout << "NULL";
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。