The issue is an "Access violation writing location 0x00000000" error message right after I initialize the bk
variable to NULL
. My guess is I should reserve memory space in advance to assign NULL
( something like Book bk = new Book();
) but I have not been able to figure out how to do it in C++ till now.
#ifndef Book_H
#define Book_H
struct _book;
typedef _book* Book;
Book CreateBook(unsigned int pageNum);
#include "Book.h"
#include <iostream>
#ifndef Book_CPP
#define Book_CPP
using namespace std;
struct _book
{
int pageNum;
};
Book CreateBook( unsigned int pageNum){
Book bk = NULL;
bk->pageNum = pageNum;
return bk;
};
You're assigning bk to NULL and then trying to access a member of it. That's the same as a null pointer in Java, and what you're doing would typically raise a NullPointerException (thanks from the comments). If you want to create a pointer to your struct, you need to use operator new:
bk = new _book;
// ...
return bk;
and then make sure you call delete on the pointer when you're done with it.
I would advise against using pointers here, though. Unlike other languages, C++ lets you create objects by value. It also allows for references and pointers, but only use pointers when you absolutely must. If you simply want to create a book object with a given pageNum, you should create a constructor while you're at it:
struct _book {
int pageNum;
_book(int n) : pageNum(n) // Create an object of type _book.
{
}
};
and then you can invoke it like
_book myBook(5); // myBook.pageNum == 5
If you're new to C++, please get yourself a good book on it. It's not just a low-level language, and it's also not just an OOP language. It's a multi-paradigm swiss army knife language.
This is what you need:
Book CreateBook( unsigned int pageNum){
Book bk = new _book();
bk->pageNum = pageNum;
return bk;
}
your bk was null and you cannot access pageNum when the pointer is null.
And don't forget to call delete on bk when you are done using it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With