我有一個定義的結構包含一個std :: list。在我的代碼中,我嘗試遍歷這個列表,但是我得到了一些奇怪的結果。std :: list.begin()給出空指針
struct my_struct_t {
std::list<int> my_list;
//More fields
};
這是我在我的頭文件中定義的結構。
而且在一個文件中的一些示例代碼,其中包括這頭將是:
std::list<int>::iterator my_iterator;
struct my_struct_t* test_struct = (struct my_struct_t*) malloc(sizeof(struct my_struct_t));
my_iterator = test_struct->my_list.begin();
printf("Beginning of list address: %p\n", my_iterator);
my_iterator = test_struct->my_list.end();
printf("End of the list address: %p\n", my_iterator);
printf("Address of the list: %p\n", &(test_struct->my_list));
此代碼編譯並運行正常,但輸出會是這樣的:
Beginning of list address: (nil)
End of the list address: 0x86f010
Address of the list: 0x86f010
最後兩行對我來說非常有意義,因爲列表應該是空的。但是如何/爲什麼我會在開始時得到一個空指針?我怎樣才能解決這個問題?
第1步:閱讀一個很好的C++入門,從[那些]中選擇一個(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。第2步:意識到儘管有許多相似之處,但C++和C語言卻是截然不同的,只是其缺陷非常相似。 – 2013-02-20 07:23:31